簡體   English   中英

在正則表達式python末尾查找帶有模式的字符串

[英]find string with a pattern at the end regex python

我想檢查字符串是否以“ _INT”結尾。

這是我的代碼

nOther = "c1_1"

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

輸出:

c101
c102
c103
c104

但是字符串中可能有兩個下划線,我只對最后一個感興趣。

如何編輯我的代碼來處理此問題?

使用兩步是沒有用的(檢查模式是否匹配,進行替換),因為re.sub一步即可:

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

該模式使用先行(?=...) (即后跟) ,它只是一個檢查,並且其中的內容不是匹配結果的一部分。 (換句話說, \\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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM