2015-09-16 182 views
1

我使用正则表达式一个的结果,建立另一个正则表达式,或多或少是这样,它会自动逃跑或者忽略特殊字符:编译正则表达式

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中找到任何内容。

+0

你在这个问题的例子是一个坏榜样。在这种情况下,'stuff'和'thing'是固定的字符串,所以不会出现特殊字符的问题。 – nhahtdh

+0

我编辑它以使其对未来的人更清楚。它只是一个占位符。 – blaineh

+0

我知道它是占位符,但其他人可能不是。你需要证明一个可重现的问题,使其成为一个很好的问题。 – nhahtdh

回答

1

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)