我正在尝试使用 re 来匹配以“\n”开头的模式,后跟可能的“real(r8)”,后跟零个或多个空格,然后是通过“功能”一词,然后我想在匹配发生的地方拆分字符串。所以对于这个字符串,
text = '''functional \n function disdat \nkitkat function wakawak\nreal(r8) function noooooo \ndoit'''
我愿意:
['functional ',
' disdat \nkitkat function wakawak',
' noooooo \ndoit']
但是,
regex = re.compile(r'''\n(real\(r8\))?\s*\bfunction\b''')
regex.split(text)
返回
['functional ',
None,
' disdat \nkitkat function wakawak',
'real(r8)',
' noooooo \ndoit']
split
也返回匹配项的组。我如何要求它不这样做?
最佳答案
你可以像这样使用非捕获组
>>> regex = re.compile(r'\n(?:real\(r8\))?\s*\bfunction\b')
>>> regex.split(text)
['functional ', ' disdat \nkitkat function wakawak', ' noooooo \ndoit']
注意 ?:
在 (?:real\(r8\))
中。引用 Python documentation for (?:..)
A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.
关于python - 如何避免在 RegEx 拆分结果中捕获组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29271447/