我正在使用一个正则表达式的结果来构建另一个正则表达式,或多或少像这样:
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)
这种方法工作正常,但有时会抛出此错误:
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
我相当有信心这是因为我正在搜索并用作新正则表达式的内容中包含无效的字符或序列,但我不确定如何解决这个问题。我是否可以传递一个参数,本质上告诉它将所有字母编译为文字而不是特殊字符?到目前为止,我还没有在 python regex guide 中找到任何内容。 .
最佳答案
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)
关于python - 编译一个将自动转义或忽略特殊字符的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32598118/