我的正则表达式没有选择与内部文本最接近的’cont’对.我该如何解决这个问题?
输入:
- cont cont ItextI /cont /cont
正则表达式:
- cont.*?I(.*?)I.*?/cont
比赛:
- cont cont ItextI /cont
匹配我需要:
- cont ItextI /cont
- cont(?:(?!/?cont).)*I(.*?)I(?:(?!/?cont).)*/cont
只会匹配最里面的块.
说明:
- cont # match "cont"
- (?: # Match...
- (?!/?cont) # (as long as we're not at the start of "cont" or "/cont")
- . # any character.
- )* # Repeat any number of times.
- I # Match "I"
- (.*?) # Match as few characters as possible,capturing them.
- I # Match "I"
- (?: # Same as above
- (?!/?cont)
- .
- )*
- /cont # Match "/cont"
这明确禁止在开头的cont和要捕获的文本之间(以及在该文本和结束/续)之间出现cont或/ cont.