Search code examples
iosobjective-cregexnsattributedstringnsmutableattributedstring

What's wrong with this Objective-C regex?


I'm trying to detect any words between asterisks:

NSString *questionString = @"hello *world*";
NSMutableAttributedString *goodText = [[NSMutableAttributedString alloc] initWithString:questionString]; //should turn the word "world" blue

    NSRange range = [questionString rangeOfString:@"\\b\\*(.+?)\\*\\b" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
    if (range.location != NSNotFound) {
        DLog(@"found a word within asterisks - this never happens");
        [goodText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
    }

But I never get a positive result. What's wrong with the regex?


Solution

  • @"\\B\\*([^*]+)\\*\\B"
    

    should achieve what you expect.

    You have to use \B in place of \b for word boundaries, as per Difference between \b and \B in regex.

    Finally, using [^*]+ matches each pair of asterisks, instead of the outermost only.

    For instance, in the string

    Hello *world* how *are* you

    it will correctly match world and are, instead of world how are.

    Another way for achieving the same is using ? which will make the + non-greedy.

    @"\\B\\*(.+?)\\*\\B"
    

    Also it's worth noting that rangeOfString:options returns the range of the first match, whereas if you are interested in all the matches you have to use build a NSRegularExpression instance with that pattern and use its matchesInString:options:range: method.