Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-greedy NSRegularExpression

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.

like image 632
baudot Avatar asked Feb 19 '12 21:02

baudot


People also ask

What is a non-greedy regex?

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.

Which regex performs a minimal non-greedy match?

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."

How do you make a non-greedy python regex?

Add a question mark (?) to a quantifier to turn it into a non-greedy quantifier.

Why is regex greedy?

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.


1 Answers

Add the question mark:

B.*?B

See table 2 in the reference of NSRegularExpression

like image 99
MByD Avatar answered Oct 04 '22 10:10

MByD