Escaping regex string

后端 未结 4 1852
时光说笑
时光说笑 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:13

    You can use re.escape():

    re.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.

    >>> import re
    >>> re.escape('^a.*$')
    '\\^a\\.\\*\\$'
    

    If you are using a Python version < 3.7, this will escape non-alphanumerics that are not part of regular expression syntax as well.

    If you are using a Python version < 3.7 but >= 3.3, this will escape non-alphanumerics that are not part of regular expression syntax, except for specifically underscore (_).

提交回复
热议问题