4

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?

Morpheu5
  • 2,610
  • 6
  • 39
  • 72
  • 2
    How does your regex code look? It should look like this `[NSRegularExpression regularExpressionWithPattern:@"([0-9]+)\\(([0-9]+),([0-9]+)\\)" options:0 error:NULL];`. Note the *double* backslashes in the pattern. – David Rönnqvist Mar 12 '13 at 22:08
  • Oh, dear. What manner of sorcery is that? Well, of course, double backslashes, good old C… :-S Please, post this as an answer :) – Morpheu5 Mar 12 '13 at 22:14

2 Answers2

7

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.

David Rönnqvist
  • 56,267
  • 18
  • 167
  • 205
2

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.

Sergiu Toarca
  • 2,697
  • 20
  • 24
  • Thanks, the whole double backslash business just slipped through as I frustratingly kept going back and forth testing the regex. I'll make sure to have a Post-It on my screen about it in the future :) – Morpheu5 Mar 12 '13 at 22:27