簡體   English   中英

用python中的另一個字符串替換字符串的某些出現

[英]Substitution of certain occurences of a string with another string in python

很抱歉,如果有人已發布相同的問題,但我無法找到它。

我試圖用其他東西替換某些字符串模式的出現。 問題我不想替換所有事件,只是除了一個。

例如。 想象一下,我有字符串: '(M:2,Seq0:2):10,Seq1:20,(Seq2:40,Seq3:40)'我想找到的模式是: '\\w+\\d+:\\d' (參考Seq[number]

想象一下,我想在'Seq[number]:'之后更改所有數字'Seq[number]:'但不是后面的那個,例如'Seq1:'

想象一下,在Seq[number]:之后的所有這些數字Seq[number]:我想要將值10加起來

在最后我想有字符串:

'(M:2,Seq0:12):10,Seq1:20,(Seq2:50,Seq3:50)'

有沒有辦法在循環中這樣做? 我嘗試使用re.findall,但它返回文本中的所有出現。 我怎么能把它合並到一個循環中?

謝謝!

您可以使用帶有函數的re.sub作為替換,例如:

>>> import re
>>> s = '(M:2,Seq0:2):10,Seq1:20,(Seq2:40,Seq3:40)'
>>> def repl(match):
...     return match.group(1) + str(int(match.group(2)) + 10)
...
>>> re.sub(r'(\w+(?!1:)\d+:)(\d+)', repl, s)
'(M:2,Seq0:12):10,Seq1:20,(Seq2:50,Seq3:50)'

Seq1:不匹配的限制由否定前瞻(?!1:) ,捕獲組僅用於將要修改的字符串部分與其余部分分開。 替換函數然后返回組1不變加上組2加上10的值。

正如Cilyan在評論中所建議的那樣,您還可以在替換函數中添加限制以不替換Seq1:這簡化了正則表達式。 這是這樣的:

def repl(match):
    if match.group(1) == 'Seq1:':
        return match.group(0)
    return match.group(1) + str(int(match.group(2)) + 10)

result = re.sub(r'(\w+\d+:)(\d+)', repl, s)

編輯:為了解決你的評論中的問題,這里是你如何寫這個來修改你添加的數字和應該忽略哪個前綴(如Seq1 :):

def make_repl(n, ignore):
    def repl(match):
        if match.group(1) == ignore:
            return match.group(0)
        return match.group(1) + str(int(match.group(2)) + n)
    return repl

result = re.sub(r'(\w+\d+:)(\d+)', make_repl(10, 'Seq1:'), s)

暫無
暫無

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

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