Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSRegularExpression acts weird (and the regex is correct)

I've got this regex

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

that I'm using to construct a NSRegularExpression with no options (0). That expression should match strings like

1(135,252)

and yield three matches: 1, 135, 252. Now, I've 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 in saying

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

which is clearly wrong.

Thoughts?

like image 501
Morpheu5 Avatar asked Jan 14 '23 23:01

Morpheu5


1 Answers

Your regex should look like this

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

Note the double backslashes in the pattern. They are needed because the backslash is used to escape special characters (like for example quotes) in C and Objective-C is a superset of C.


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

like image 74
David Rönnqvist Avatar answered Jan 19 '23 12:01

David Rönnqvist