如何在python正则表达式代码中包含[]?

时间:2016-02-15 12:23:15

标签: python-2.7

我正在使用python 2.7.8编写一个小的python代码,该代码以A ==>形式读取规则。 B使用正则表达式并以“A,B'”的形式返回。 这是我的代码:

import re

def fixp1(s):
    pattern = re.compile("(?P<g1>([A-Z0-9a-z]|\?)*):(?P<g2>([A-Z0-9a-z]|\?)*)")
    return eval(pattern.sub("('\g<g1>', '\g<g2>')", s))

x = "[ABCD:NP, [PQR:?TAG1]] ==> [XXX:?P]"

def readrule(r):
    r.split("==>")
    return [fixp1(r[0].strip()), fixp1(r[1].strip())]

当我测试这段代码时:

>>> readrule(x)

我收到以下错误消息:

readrule(y)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File ".../patterns.py", line 12, in readrule
        return [fixp1(r[0].strip()), fixp1(r[1].strip())]
    File ".../patterns.py", line 5, in fixp1
        return eval(pattern.sub("('\g<g1>', '\g<g2>')", s))
    File "<string>", line 1
        [
        ^
SyntaxError: unexpected EOF while parsing
>>> 

我认为发生这个问题是因为我无法添加&#39; [&#39;和&#39;]&#39;在这里

([A-Z0-9a-z]|\?)

如果那是对的,怎么做?如果不;我的错在哪里?

1 个答案:

答案 0 :(得分:2)

删除eval命令,RegEx。sub返回一个与应用的替换匹配的字符串,您无法评估该字符串。这会产生您所看到的SyntaxError

如果您想在模式中加入[],则需要使用\转义它们:

 pattern = re.compile(r'[\[\]0-9]+')

会匹配&#39; [1234]&#39;。

等字符串