Python中不一致的regex行为

2024-10-02 08:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个正则表达式,我已经验证了它的正确性,证明如下:https://regex101.com/r/ffSVuD/6

不幸的是,当我在一些Python代码中使用相同的regex时,我没有得到相同的行为。正则表达式确实得到匹配项,但找不到相同的匹配组。在

下面是一些演示代码:

import re
ddl_string = """
CREATE TABLE default.test_parse_partitioned_table__using_parquet_1_082921496561 (DATA4 BIGINT, DATA5 BIGINT, DATA2 BIGINT, DATA3 BIGINT)
USING parquet
OPTIONS (
  serialization.format \\'1\\'
)
PARTITIONED BY (DATA2, DATA3)
"""
regex = r'CREATE +?(TEMPORARY +)?TABLE *(?P<db>.*?\.)?(?P<table>.*?)\((?P<col>.*?)\).*?USING +([^\s]+)( +OPTIONS *\([^)]+\))?( *PARTITIONED BY \((?P<pcol>.*?)\))?'
match = re.search(regex, ddl_string, re.MULTILINE | re.DOTALL)
if match.group("pcol"):
    print match.group("pcol").strip()
else:
    print 'did not find any pcols in {matches}'.format(matches=match.groups())

返回:

did not find any pcols in (None, 'default.', 'test_parse_partitioned_table__using_parquet_1_082921496561 ', 'DATA4 BIGINT, DATA5 BIGINT, DATA2 BIGINT, DATA3 BIGINT', 'parquet', None, None, None)

我的意图是将数据2、数据3填充到match.group("pcol")中,但正如您将看到的那样,这并没有发生。在我前面提到的https://regex101.com/r/ffSVuD/6的regex验证中,它确实找到匹配项:

regex match group pcol

我已经摆弄了很多试图得到一个正则表达式,将返回我需要的,但没有成功,因此这篇文章。有人能帮忙吗?在


Tags: httpsrecomnonematchtablegroupregex

热门问题