在python正则表达式中匹配嵌入的换行符
处理这个问题的方法是什么?我尝试过字符串、原始字符串和(?is)、re.DOTALL的各种排列,但都没有成功 以下是我尝试过的示例:在python正则表达式中匹配嵌入的换行符,python,regex,multiline,Python,Regex,Multiline,处理这个问题的方法是什么?我尝试过字符串、原始字符串和(?is)、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 (.*) fr
>>> 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'
相同(结果不正确)
我也试过带/不带(?is)和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'}
>>nonewline=“从a.id不为null的联接b中选择a.b”
>>>y=re.match((?is)从(.*)中选择(.*),其中(?P.*),非WLINE,re.DOTALL | re.MULTILINE)
>>>y.groupdict()
{'where':'a.id不为null'}
我认为问题在于,实际上在where
语句前面有一个换行符,而不是空格
您的文本:
“从连接b中选择a.b\n其中a.id不为空”
--------------------------------------------^
您的正则表达式:
(?is)从(.*)中选择(.*),其中(?p.*)
-------------------------------------------^
请尝试以下方法:
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())
一旦从测试字符串中删除换行符,groupdict()就会完美地返回。我更新了问题以反映此信息。后续操作:我删除了“硬编码”空格,并用[\s]+代替它们。@javadba:我编辑了正则表达式,以便从匹配的字符串中删除空格
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'}