My goal is to match each group starting with __ and ending with __.
For example, in this text:
__1__
__2____3__
__4_4__
We can find 4 groups.
With this regex
__.[^__]*__
the last group doesn't match.
With this one
__(?!(^_)$).*__
the 2nd and 3rd groups are gathered in one.
What is the solution please?
You can use
__.+?__
You might be surprised that I didn't say anything about "don't match any underscores along the way", since in all your attempts you tried to something like that.
The trick is to use +?
, a lazy quantifier. I allow the regex to match any character ( .
), but as few times as possible , such that there are two underscores after it. It's as if after matching each character, the regex engine always asks "are there two underscores ahead?". And if there are, that's where the quantifier stops matching.
See this for more info about lazy vs greedy quantifiers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.