非贪婪的正则表达式并不是最接近的选择

前端之家收集整理的这篇文章主要介绍了非贪婪的正则表达式并不是最接近的选择前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的正则表达式没有选择与内部文本最接近的’cont’对.我该如何解决这个问题?

输入:

  1. cont cont ItextI /cont /cont

正则表达式:

  1. cont.*?I(.*?)I.*?/cont

比赛:

  1. cont cont ItextI /cont

匹配我需要:

  1. cont ItextI /cont
  1. cont(?:(?!/?cont).)*I(.*?)I(?:(?!/?cont).)*/cont

只会匹配最里面的块.

说明:

  1. cont # match "cont"
  2. (?: # Match...
  3. (?!/?cont) # (as long as we're not at the start of "cont" or "/cont")
  4. . # any character.
  5. )* # Repeat any number of times.
  6. I # Match "I"
  7. (.*?) # Match as few characters as possible,capturing them.
  8. I # Match "I"
  9. (?: # Same as above
  10. (?!/?cont)
  11. .
  12. )*
  13. /cont # Match "/cont"

这明确禁止在开头的cont和要捕获的文本之间(以及在该文本和结束/续)之间出现cont或/ cont.

猜你在找的正则表达式相关文章