簡體   English   中英

Python-如何使用正則表達式替換n次出現的子字符串

[英]Python - how to substitute a substring using regex with n occurrencies

我有一個字符串,其中包含多個重復的單個模式,例如

a = 'eresQQQutnohnQQQjkhjhnmQQQlkj'

而且我還有另一個字符串

b = 'rerTTTytu'

second string having as a reference the 'QQQ' and the 'TTT', and I want to find in this case 3 different results: 我想替換具有作為參考的“QQQ”和“TTT”的第二串,我想在這種情況下3個不同的結果中找到:

'ererTTTytuohnQQQjkhjhnmQQQlkj'
'eresQQQutnrerTTTytujhnmQQQlkj'
'eresQQQutnohnQQQjkhjrerTTTytu'

我試過使用re.sub

re.sub('\w{3}QQQ\w{3}' ,b,a)

但是我只獲得第一個,而我不知道如何獲得其他兩個解決方案。

編輯:根據您的要求,'QQQ'周圍的兩個字符也將被替換。

我不知道這是否是解決問題的最優雅或最簡單的方法,但是它可以工作:

import re

# Find all occurences of ??QQQ?? in a - where ? is any character
matches = [x.start() for x in re.finditer('\S{2}QQQ\S{2}', a)]
# Replace each ??QQQ?? with b
results = [a[:idx] + re.sub('\S{2}QQQ\S{2}', b, a[idx:], 1) for idx in matches]

print(results)

輸出量

['errerTTTytunohnQQQjkhjhnmQQQlkj',
'eresQQQutnorerTTTytuhjhnmQQQlkj',
'eresQQQutnohnQQQjkhjhrerTTTytuj']

由於您未指定輸出格式,因此將其放在列表中。

暫無
暫無

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

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