0

私はこのような状況にあり、正規表現でそれを行うことができるかどうか疑問に思っています:

次の形式の文字列があります。

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

私の質問は、正規表現の置換を使用して次を取得する方法です。

match1 love match2
4

2 に答える 2

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)

任意の数のグループで機能します。

于 2012-08-03T12:29:44.233 に答える
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
)
"""
于 2012-08-03T12:24:00.033 に答える