Escaping regex string

后端 未结 4 1906
时光说笑
时光说笑 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 00:59

    Unfortunately, re.escape() is not suited for the replacement string:

    >>> re.sub('a', re.escape('_'), 'aa')
    '\\_\\_'
    

    A solution is to put the replacement in a lambda:

    >>> re.sub('a', lambda _: '_', 'aa')
    '__'
    

    because the return value of the lambda is treated by re.sub() as a literal string.

提交回复
热议问题