1

有什么办法来处理这个?我尝试了字符串、原始字符串和 (?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 (.*) 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""""

相同(结果不正确)

我也试过带/不带 (?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'}
4

1 回答 1

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'}
于 2013-06-01T23:45:35.487 回答