1

I have the following string: "Title: " and I am using regex in Objective-C to extract the "/books/1/title" part from the string. (The string can contain multiple expressions) The regex is as follows <\?(.+?)\?>. My problem is that it matches the whole string(from index 0 to 24) and not the content between the tags. The code is as follows:

NSString *object = @"Title: <?/books/1/title?>";

NSMutableString *newString = [[NSMutableString alloc] initWithString:object];

NSString *pattern = @"<\?(.+?)\?>";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                           options:0 error:NULL];

NSArray *matches = [regex matchesInString:object options:0 range:NSMakeRange(0, [object length])];

for (NSInteger i = [matches count]-1; i>=0 ; i--) {
    NSTextCheckingResult * match = [matches objectAtIndex:i];

    if (match != nil && [match rangeAtIndex:0].location != NSNotFound && [match numberOfRanges] == 2) {

        NSRange part1Range = [match rangeAtIndex:1];
        NSLog(@"%lu %lu", (unsigned long)part1Range.location, (unsigned long)part1Range.length);
    }
}

1 Answer 1

3

It looks like you have incorrectly escaped the question marks: you used a single backslash, but Objective-C compiler needs two slashes in a string literal in order to represent a single backslash:

NSString *pattern = @"<\\?(.+?)\\?>";

Without the extra slash single slashes are not becoming part of the string, so regex engine sees this expression <?(.+?)?>, treats the opening angular bracket as optional, and then proceeds to matching the whole text up to the closing angular bracket.

One way to escape meta-characters, such as question marks and dots, is enclosing them into a character class instead of using a backslash. This expression is equivalent to yours, but it does not additional escaping of slashes:

NSString *pattern = @"<[?](.+?)[?]>";
Sign up to request clarification or add additional context in comments.

2 Comments

Solved my problem, thank you very much for a good solution and explanation.
Hard to debug unless you know how Objective-C requires regex strings (I don't!) +1 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.