re.sub公司部分字符串:(?:……)神秘

2024-10-06 09:59:36 发布

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

我有一个字符串:

temp = '4424396.6\t1\tk__Bacteria\tp__Firmicutes\tc__Erysipelotrichi\to__Erysipelotrichales'

我需要去掉分类术语之间的表格。在

我试过了

^{pr2}$

它非常接近,但也取代了制表符之前的字母:

'4424396.6\t1\tk__Bacteri,p__Firmicute,c__Erysipelotrich,o__Erysipelotrichales'

我很困惑,因为(?:...)的重新文档如下:

...the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.

最后一个字母在括号内,怎么能替换呢?在

PS公司

我使用了re.sub(r'(?<=\D{1})(\t)', ',', temp),它工作得非常好,但是我不明白第一个regexp有什么问题


Tags: theto字符串字母分类temptk术语
2条回答

根据the documentation(?:...)指定了一个非捕获组。它解释说:

Sometimes you’ll want to use a group to collect a part of a regular expression, but aren’t interested in retrieving the group’s contents.

这意味着匹配...表达式(在您的例子中,前面的字母)将不会被捕获为一个组,但仍将是匹配的一部分。唯一的特别之处是您无法使用match.group访问此组捕获的输入部分:

Except for the fact that you can’t retrieve the contents of what the group matched, a non-capturing group behaves exactly the same as a capturing group

相反,(?<=...)是一个肯定的lookbehind断言;正则表达式将检查以确保任何匹配项前面都有文本匹配...,但不会捕获该部分。在

(?:...)匹配的文本与(...)一样,不会形成一个捕获组,因此以后不能用反向引用(如\1)来引用。但是,它仍然是整个匹配的一部分,并且是re.sub()将替换的文本的一部分。在

非捕获组的意义在于它们的效率稍高一些,在诸如re.split()这样的应用中可能需要它们,因为捕获组的存在会影响输出。在

相关问题 更多 >