通过正则表达式匹配字符串中不匹配的部分
Match unmatched part of string by regexp
我有一个像这样的 HTML 字符串...
Lorem Ipsum<span class="removed">removed</span><span class="added">added </span>lorem ipsum
我想放置不在跨度中的字符串,所以我想要它
<span class="normal">Lorem Ipsum</span><span class="removed">removed</span><span class="added">added </span><span class="normal">lorem ipsum</span>
我可以分解所有字符串并再次与一些代码行组合,但我想问一下这是否可以使用正则表达式?
谢谢!
请注意,正则表达式已针对特定情况进行了简化,并且可能会得到改进以处理更复杂的情况(cdata、评论、引号等)
搜索
<span(?>[^>]*>.*?<\/span>)(*SKIP)(?!)|([^<]*)
替换为
<span class="normal"></span>
工作原理
- 1 : 匹配我们不想要的
<span(?>[^>]*>.*?<\/span>)
- 2 : 使用回溯动词来避免回溯和匹配失败
(*SKIP)(?!)
- 3 : 接下来交替选择一个不能匹配第一部分的模式
我有一个像这样的 HTML 字符串...
Lorem Ipsum<span class="removed">removed</span><span class="added">added </span>lorem ipsum
我想放置不在跨度中的字符串,所以我想要它
<span class="normal">Lorem Ipsum</span><span class="removed">removed</span><span class="added">added </span><span class="normal">lorem ipsum</span>
我可以分解所有字符串并再次与一些代码行组合,但我想问一下这是否可以使用正则表达式?
谢谢!
请注意,正则表达式已针对特定情况进行了简化,并且可能会得到改进以处理更复杂的情况(cdata、评论、引号等)
搜索
<span(?>[^>]*>.*?<\/span>)(*SKIP)(?!)|([^<]*)
替换为
<span class="normal"></span>
工作原理
- 1 : 匹配我们不想要的
<span(?>[^>]*>.*?<\/span>)
- 2 : 使用回溯动词来避免回溯和匹配失败
(*SKIP)(?!)
- 3 : 接下来交替选择一个不能匹配第一部分的模式