Escaping regex string

后端 未结 4 1902
时光说笑
时光说笑 2020-11-22 00:36

I want to use input from a user as a regex pattern for a search over some text. It works, but how I can handle cases where user puts characters that have meaning in regex?<

4条回答
  •  耶瑟儿~
    2020-11-22 01:08

    Use the re.escape() function for this:

    4.2.3 re Module Contents

    escape(string)

    Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

    A simplistic example, search any occurence of the provided string optionally followed by 's', and return the match object.

    def simplistic_plural(word, text):
        word_or_plural = re.escape(word) + 's?'
        return re.match(word_or_plural, text)
    

提交回复
热议问题