NSRegularExpression acts weird (and the correct regular expression)

I have this regex

([0-9]+)\(([0-9]+),([0-9]+)\) 

which I use to build NSRegularExpression without parameters (0). This expression must match strings of type

 1(135,252) 

and we get three matches: 1, 135, 252. Now I confirmed with debuggex.com that the expression is correct and does what I want. However, iOS refuses to acknowledge my efforts and the following code.

 NSString *nodeString = @"1(135,252)"; NSArray *r = [nodeRegex matchesInString:nodeString options:0 range:NSMakeRange(0, nodeString.length)]; NSLog(@"--- %@", nodeString); for(NSTextCheckingResult *t in r) { for(int i = 0; i < t.numberOfRanges; i++) { NSLog(@"%@", [nodeString substringWithRange:[t rangeAtIndex:i]]); } } 

insists on saying

 --- 1(135,252) 135,252 13 5,252 5 252 

which is clearly wrong.

Thoughts?

+4
source share
2 answers

Your regex should look like this

 [NSRegularExpression regularExpressionWithPattern:@"([0-9]+)\\(([0-9]+),([0-9]+)\\)" options:0 error:NULL]; 

Notice the double backslash in the pattern. They are necessary because the backslash is used to call special characters (such as quotation marks) in C and Objective-C is a superset of C.


If you are looking for a convenient tool for working with regular expressions, I can recommend Patterns . Its very cheap and can export directly to NSRegularExpressions .

+7
source

Currently, Debuggex only supports raw regular expressions. This means that if you use a regular expression in a string, you need to avoid backslashes, for example:

([0-9]+)\\(([0-9]+),([0-9]+)\\)

Also note that Debuggex does not support Objective C. This probably doesn't matter for simple regular expressions, but for more complex ones, different engines do different things. This can lead to unexpected behavior.

+2
source

Source: https://habr.com/ru/post/1468843/


All Articles