Python 编译一个将自动转义或忽略特殊字符的正则表达式

Python 编译一个将自动转义或忽略特殊字符的正则表达式,python,regex,Python,Regex,我使用一个正则表达式的结果构建另一个正则表达式,大致如下: regex = '(?P<prev>.+?)(?P<hook>\%\%.+?\%\%)(?P<next>.+?$)' match = re.search(regex, content, re.S) comparisonRegex = match.group('prev') + '(?P<desiredContent>desireable)' + match.group('nex

我使用一个正则表达式的结果构建另一个正则表达式,大致如下:

regex = '(?P<prev>.+?)(?P<hook>\%\%.+?\%\%)(?P<next>.+?$)'
match = re.search(regex, content, re.S)

comparisonRegex = match.group('prev') + 
    '(?P<desiredContent>desireable)' + match.group('next')
match = re.search(comparisonRegex, otherContent, re.S)
我很有信心这是因为我正在搜索并用作新正则表达式的内容中包含无效字符或序列,但我不确定如何处理。是否有一个我可以传递的参数,基本上告诉它将所有字母编译为文字而不是特殊字符?到目前为止,我还没有在数据库中找到任何东西。

regex='(?P.?+)(\%\%\%.+?\%\%)(?P.+?$)'
匹配=重新搜索(regex、content、re.S)
comparisonRegex=re.escape(match.group('prev'))+
“(?Pdesireable)”+re.escape(match.group('next'))
match=re.search(comparisonRegex、otherContent、re.S)

你在这个问题上的例子是一个糟糕的例子。由于
stuff
thing
在本例中是固定字符串,特殊字符的问题永远不会发生。我对其进行了编辑,以使将来的人更清楚地了解它。它只是一个占位符。我知道它是占位符,但其他人可能不会。你需要证明一个可重复的问题,使之成为一个好问题。
  File "/path/to/my/script/refactor_static.py", line 92, in dynamicContent
    match = re.search(comparisonRegex, crawlFileContent, re.S)
  File "/usr/lib/python2.7/re.py", line 142, in search
    return _compile(pattern, flags).search(string)
  File "/usr/lib/python2.7/re.py", line 244, in _compile
    raise error, v # invalid expression
sre_constants.error: bad character range
regex = '(?P<prev>.?+)(\%\%.+?\%\%)(?P<next>.+?$)'
match = re.search(regex, content, re.S)

comparisonRegex = re.escape(match.group('prev')) + 
    '(?P<desiredContent>desireable)' + re.escape(match.group('next'))
match = re.search(comparisonRegex, otherContent, re.S)