Python无法编译regex

2024-09-30 12:29:24 发布

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

我尝试使用python regex从cmake文件中检测所有set,用于以下文件:

# Library to include
set(LIB_TO_INCLUDE 
        a
        b
        c)

# comon code (inclusion in source code)
set(SHARED_TO_INCLUDE d e f)

# Library to include
set(THIRD_PARTY g h)

我想取回:

^{pr2}$

我使用regex101.com测试了regex set\((?s:[^)])*?\)(除了)项之外,set(后面的所有项),它显然做了我想要的。在

现在,当我试图从Python运行re.compile(r'set\((?s:[^)])*?\)')时,我得到一个错误:

  File "private\python_scripts\convert.py", line 34, in create_sde_files
    pattern = re.compile(r'set\((?s:[^)])*?\)')   File "b:\dev\vobs_ext_2015\tools_ext\python\Python34_light\lib\re.py", line 223, in compile
    return _compile(pattern, flags)   File "b:\dev\vobs_ext_2015\tools_ext\python\Python34_light\lib\re.py", line 294, in _compile
    p = sre_compile.compile(pattern, flags)   File "b:\dev\vobs_ext_2015\tools_ext\python\Python34_light\lib\sre_compile.py", line 568, in compile
    p = sre_parse.parse(p, flags)   File "b:\dev\vobs_ext_2015\tools_ext\python\Python34_light\lib\sre_parse.py", line 760, in parse
    p = _parse_sub(source, pattern, 0)   File "b:\dev\vobs_ext_2015\tools_ext\python\Python34_light\lib\sre_parse.py", line 370, in _parse_sub
    itemsappend(_parse(source, state))   File "b:\dev\vobs_ext_2015\tools_ext\python\Python34_light\lib\sre_parse.py", line 721, in _parse
    raise error("unknown extension") sre_constants.error: unknown extension

Python不支持这种正则表达式吗?在


Tags: inpydevparseliblinetoolsext
1条回答
网友
1楼 · 发布于 2024-09-30 12:29:24

应该这样做:set\(([^)]*?)\)

编译正则表达式时,“单行”修饰符作为参数传递:

>>> t = """set(LIB_TO_INCLUDE 
...         a
...         b
...         c)"""
>>> 
>>> pattern = r'set\(([^)]*?)\)'
>>> 
>>> regex = re.compile(pattern, re.S)
>>> 
>>> result = regex.search(t).groups()[0]
>>> result
'LIB_TO_INCLUDE \n        a\n        b\n        c'

然后可以消除多余的间距和新行:

^{pr2}$

请注意,在您的链接中,如果您在左边的“风格”中切换到“python”,您将得到您的特定格式导致的错误。在

编辑:要获得所有(3)个匹配项,您需要使用<regex>.findall(...)而不是{}。在

>>> tt = """# Library to include
... set(LIB_TO_INCLUDE 
...         a
...         b
...         c)
... 
... # comon code (inclusion in source code)
... set(SHARED_TO_INCLUDE d e f)
... 
... # Library to include
... set(THIRD_PARTY g h)"""
>>> 

>>> result = regex.findall(tt)
>>> result
['LIB_TO_INCLUDE \n        a\n        b\n        c', 'SHARED_TO_INCLUDE d e f', 'THIRD_PARTY g h']

相关问题 更多 >

    热门问题