处理此问题的方法是什么?我已经尝试了各种字符串,原始字符串和(?是),re.DOTALL的排列,但一直都是不成功的。
以下是我尝试过的一个示例:
>>> x="select a.b from a join b \nwhere a.id is not null"
>>> print (x)
select a.b from a join b
where a.id is not null
>>> y=re.match("(?is)select (.*) from (.*) where (?P<where>.*)",x,re.DOTALL)
>>> y.groupdict()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'groupdict'
注意也尝试过:
>>> x=r"""select a.b from a join b
where a.id is not null""""
相同(不正确的结果)
我也试过/没有(?是)和re.DOTALL。
注意:如果从测试的字符串中删除了嵌入的换行符,那么匹配就完美了:
>>> nonewline="select a.b from a join b where a.id is not null"
>>> y=re.match("(?is)select (.*) from (.*) where (?P<where>.*)",nonewline,re.DOTALL|re.MULTILINE)
>>> y.groupdict()
{'where': 'a.id is not null'}
答案 0 :(得分:2)
我认为问题是你实际上在where
语句之前有一个换行符,而不是空格。
您的文字:
"select a.b from a join b \nwhere a.id is not null"
-------------------------------------------- ^
你的正则表达式:
(?is)select (.*) from (.*) where (?P<where>.*)
------------------------------------------- ^
尝试这样的事情:
from re import *
x = "select a.b from a join b \nwhere a.id is not null"
y = match("select\s+(.*?)\s+from\s+(.*?)\s+where\s+(?P<where>.*)",
x, DOTALL)
print(y.groups())
print(y.groupdict())
输出:
('a.b', 'a join b', 'a.id is not null')
{'where': 'a.id is not null'}