gpt4 book ai didi

python - re.sub 字符串 : (? : . ..) 的一部分

转载 作者:行者123 更新时间:2023-11-30 22:43:30 25 4
gpt4 key购买 nike

我有一个字符串:

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

我只需要删除分类术语之间的表格。

我试过了

re.sub(r'(?:\D{1})\t', ',', temp)

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

'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.

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

附注

我用过re.sub(r'(?<=\D{1})(\t)', ',', temp)它工作得很好,但我不明白第一个正则表达式出了什么问题

最佳答案

(?:...)匹配的文本不形成捕获组(...)也是如此,因此稍后不能使用诸如 \1 之类的反向引用来引用。但是,它仍然是整体匹配的一部分,并且是 re.sub() 将替换的文本的一部分。

非捕获组的要点是它们的效率稍微高一些,并且在诸如 re.split() 之类的使用中可能需要它们,其中捕获组的存在就会影响输出。

关于python - re.sub 字符串 : (? : . ..) 的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41746290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com