我遇到這種情況,我想知道如果我可以用正則表達式做替換匹配:正則表達式:與他們的IDS
我在這個格式的字符串:
{{We all}} love {{stackoverflow}}.
我的問題是我該如何使用正則表達式替換獲得:
match1 love match2
我遇到這種情況,我想知道如果我可以用正則表達式做替換匹配:正則表達式:與他們的IDS
我在這個格式的字符串:
{{We all}} love {{stackoverflow}}.
我的問題是我該如何使用正則表達式替換獲得:
match1 love match2
s = '{{We all}} love {{stackoverflow}}.' #string to match
pat = re.compile(r'\{\{.*?\}\}') #pattern
#now replace each matched group by its index
for index,group in enumerate(re.findall(pat,s)):
s = re.sub(group, 'match'+str(index+1), s)
適用於任何數量的組。
試試這個
result = re.sub("([{]{2}[^}]+[}]{2})([^{]+)([{]{2}[^}]+[}]{2})", r"match1\2match2", subject)
解釋
"""
( # Match the regular expression below and capture its match into backreference number 1
[{] # Match the character 「{」
{2} # Exactly 2 times
[^}] # Match any character that is NOT a 「}」
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
[}] # Match the character 「}」
{2} # Exactly 2 times
)
( # Match the regular expression below and capture its match into backreference number 2
[^{] # Match any character that is NOT a 「{」
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
( # Match the regular expression below and capture its match into backreference number 3
[{] # Match the character 「{」
{2} # Exactly 2 times
[^}] # Match any character that is NOT a 「}」
+ # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
[}] # Match the character 「}」
{2} # Exactly 2 times
)
"""
只適用於2組 – Lanaru 2012-08-03 12:30:21
[你有什麼嘗試?](http://whathaveyoutried.com)假設你想要替換的項目之外沒有其他大括號,這應該是一件簡單的事情。拿起一個或兩個正則表達式教程,看看一些文檔。 – 2012-08-03 12:12:35
我正在使用Python。將嘗試看看建議的一些教程:) – 2012-08-03 12:13:58