Morpheu5
Morpheu5

Reputation: 2801

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?

Upvotes: 4

Views: 626

Answers (2)

David R&#246;nnqvist
David R&#246;nnqvist

Reputation: 56625

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.

Upvotes: 7

Sergiu Toarca
Sergiu Toarca

Reputation: 2759

Debuggex currently supports only raw regexes. This means that if you are using the regex in a string, you need to escape your backslashes, like this:

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

Also note that Debuggex does not (yet) support Objective C. This probably won't matter for simple regexes, but for more complicated ones, different engines do different things. This can result in some unexpected behavior.

Upvotes: 2

Related Questions