在最后的正则表达式python中找到带有模式的字符串

时间:2014-06-02 16:09:41

标签: python regex string compilation

我想检查字符串是否以" _INT"结尾。

这是我的代码

nOther = "c1_1"

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

输出:

c101
c102
c103
c104

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

如何编辑代码来处理此问题?

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

一种方法是捕获不是最后一个下划线的所有内容并重建字符串。

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
相关问题