如何通过正则表达式捕获特定标记内的所有标记?

时间:2012-05-29 09:55:59

标签: python regex

例如,有一个像

这样的代码
<tag1 blablablah>sometext<i>sometext</i>sometext<i>sometext</i>sometext</tag1>

我想做的就是把它变成

<tag1 blablablah>sometext<XXX><i></XXX>sometext<XXX></i></XXX>sometext<XXX><i></XXX>sometext<XXX></i></XXX>sometext</tag1>

我正在使用正则表达式进行搜索(它也适用于Notepad ++和Python的re.compile函数)

(<tag1[^>]*>.*?)(<[^>]*>.*?)(.*?</tag1>)

替换(也适用于re.sub)

\1<XXX>\2</XXX>\3

但是它只发现并改变了第一次出现而不是全部......

<tag1 blablablah>sometext<XXX><i></XXX>sometext</i>sometext<i>sometext</i>sometext</tag1>

任何人都可以帮我吗?

3 个答案:

答案 0 :(得分:2)

试试这个

<((?:[a-z]+:)?[a-z]\w+)\b[^<>]+?>(.+)</\1>

<强>解释

"
<              # Match the character “<” literally
(              # Match the regular expression below and capture its match into backreference number 1
   (?:            # Match the regular expression below
      [a-z]          # Match a single character in the range between “a” and “z”
         +              # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
      :              # Match the character “:” literally
   )?             # Between zero and one times, as many times as possible, giving back as needed (greedy)
   [a-z]          # Match a single character in the range between “a” and “z”
   \w             # Match a single character that is a “word character” (letters, digits, and underscores)
      +              # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
\b             # Assert position at a word boundary
[^<>]          # Match a single character NOT present in the list “<>”
   +?             # Between one and unlimited times, as few times as possible, expanding as needed (lazy)
>              # Match the character “>” literally
(              # Match the regular expression below and capture its match into backreference number 2
   .              # Match any single character that is not a line break character
      +              # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
</             # Match the characters “</” literally
\1             # Match the same text as most recently matched by capturing group number 1
>              # Match the character “>” literally
"

答案 1 :(得分:0)

问题是避免使用第一个和最后一个标签。如果你把它们分开,那就很简单了:

s = '<tag1 blablablah>sometext<i>sometext</i>sometext<i>sometext</i>sometext</tag1>'
start, end = s.find('>') + 1, s.rfind('<')
s_list = [s[:start], s[start:end], s[end:]]
s_list[1] = re.sub(r'(<[^>]*>)', r'<XXX>\1</XXX>', s_list[1])
print ''.join(s_list)
但是,这不是一个单行。

或者,你可以这样做:

print re.sub(r'([^(^<)])(<[^>]*>(?!$))', r'\1<XXX>\2</XXX>', s)

请注意,这仅适用于最外面的标签位于字符串的开头和结尾处。

答案 2 :(得分:0)

尝试像这样改变你的模式

(<tag1[^>]*>).*?(<[^>]+>).*?(</tag1>)