如果找不到给定的文本并匹配尽可能少的正则表达式

Regex to match if given text is not found and match as little as possible

我有文字:

<a>
sdfsdf
<b>DDzz</b>
sdfsdf
</a>
<a>
sdfsdf
<b>DDzz</b>
sdfsdf
</a>
<a>
sdfsdf
<b>BBzz</b>
sdfsdf
</a>
<a>
sdfsdf
<b>DDzz</b>
sdfsdf
</a>

我无法将其解析为 xml。我需要在这里使用正则表达式。这也只是示例。

我想要的正则表达式可以将不包含元素 b 的每个组 <a>...</a> 与以 BB.

开头的文本相匹配

我想出了这个正则表达式: <a>.*?<b>(?!B).*?</b>.*?</a> 但它与最后一组匹配为:

<a>
sdfsdf
<b>BBzz</b>
sdfsdf
</a>
<a>
sdfsdf
<b>DDzz</b>
sdfsdf
</a>

这对我不利。

如何编写仅匹配我给定示例中的那 3 组的正则表达式?

1.

<a>
sdfsdf
<b>DDzz</b>
sdfsdf
</a>

2.

<a>
sdfsdf
<b>DDzz</b>
sdfsdf
</a>

3.

<a>
sdfsdf
<b>DDzz</b>
sdfsdf
</a>

使用 正则表达式:

<a>(?:(?!<(?:b>BB|/?a>)).)*</a>

启用 . 匹配换行符 选项。

详情:

  • <a> - 文字 <a> 字符序列
  • (?:(?!<(?:b>BB|/?a>)).)* - 匹配任何字符 (.) 的缓和贪婪标记,它不是序列的起始符号,可以与 (?!<(?:b>BB|/?a>)) 前瞻 (不是 <b>BB</a><a> 序列)
  • </a> - 文字 </a> 字符序列