正则表达式:用他们的id替换匹配

时间:2012-08-03 12:11:12

标签: python regex

我遇到这种情况,我想知道我是否可以用正则表达式做到这一点:

我有一个这种格式的字符串:

{{We all}} love {{stackoverflow}}.

我的问题是如何使用正则表达式取代:

match1 love match2

2 个答案:

答案 0 :(得分:1)

试试这个

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
)
"""

答案 1 :(得分:1)

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)

适用于任意数量的群体。