查找在regex python结尾带有模式的字符串

2024-06-24 11:55:53 发布

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

我想检查字符串是否以“\u INT”结尾。你知道吗

这是我的密码

nOther = "c1_1"

tail = re.compile('_\d*$')
if tail.search(nOther):
    nOther = nOther.replace("_","0")
print nOther

输出:

c101
c102
c103
c104

但是字符串中可能有两个下划线,我只对最后一个感兴趣。你知道吗

如何编辑代码来处理此问题?你知道吗


Tags: 字符串re密码searchif结尾replaceint
2条回答

使用两个步骤是无用的(检查模式是否匹配,进行替换),因为re.sub只需一个步骤:

txt = re.sub(r'_(?=\d+$)', '0', txt)

模式使用一个lookahead(?=...)(即后跟),它只是一个检查,里面的内容不是匹配结果的一部分。(换句话说\d+$不被替换)

一种方法是捕获不是最后一个下划线的所有内容并重新生成字符串。你知道吗

import re

nOther = "c1_1"

tail = re.compile('(.*)_(\d*$)')

tail.sub(nOther, "0")
m = tail.search(nOther)
if m:
    nOther = m.group(1) + '0' + m.group(2)
print nOther

相关问题 更多 >