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

标签 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('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 中找到任何内容。 .

最佳答案

re.escape

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/

相关文章:

python - 箱线图:索引超出范围错误

python - 无法在 Flask 的生产服务器中启用 Debug模式

javascript - 验证 javascript 十进制数

php - 正则表达式匹配 1 个 HTML 文件中的 2 个 html 标签

Javascript正则表达式或疑问

c# - .Net Regex.Escape 无法正常工作?

Python:ctypes加载的dll是否共享相同的内存空间

python - urllib.request.urlretrieve 尝试在 Python 中下载 jpeg 时出错

python - 如何阻止 '\n' 或 '\t' 在字符串中工作?

javascript - 如何在保留边界字符的情况下分割字符串?