I'm need an NSRegularExpression that matches non-greedily. You know, if there's:
ABABABA
...and I ask it to match B.*B
I want it to grab the SMALLEST possible match: BAB
, not BABAB
.
I've been googling this for an hour now, and I keep finding references to the ICU/XCode regex implementation having support for non-greedy matching, but for the life of me, I can't find the syntax to actually do it anywhere.
A non-greedy match means that the regex engine matches as few characters as possible—so that it still can match the pattern in the given string.
Here is the description of the regex "+?" from the python docs: "Adding '?' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched."
Add a question mark (?) to a quantifier to turn it into a non-greedy quantifier.
The default behavior of regular expressions is to be greedy. That means it tries to extract as much as possible until it conforms to a pattern even when a smaller part would have been syntactically sufficient. Instead of matching till the first occurrence of '>', it extracted the whole string.
Add the question mark:
B.*?B
See table 2 in the reference of NSRegularExpression
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With