2

I am trying to detect the following expression: $

for example

$john

or

$mike

What is wrong with my regex?

//Check for $symbol
    NSRegularExpression *symbolRegex = [[NSRegularExpression alloc] initWithPattern:@"($[a-zA-Z0-9_]+)" 
                                                                              options:NSRegularExpressionCaseInsensitive 
                                                                                error:nil];
    matches = [symbolRegex matchesInString:labelText options:0 range:NSMakeRange(0, [labelText length])];

    for (NSTextCheckingResult *result in matches) {
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"symbol://%@",[labelText substringWithRange:result.range]]];
        [bodyLabel addCustomLink:url inRange:[result range]];        
    }

    [symbolRegex release];

1 Answer 1

3

It looks like you need to escape the $.

(\\$[a-zA-Z0-9_]+)

$ (dollar)

Matches at the end of the string the regex pattern is applied to. Matches a position rather than a character. Most regex flavors have an option to make the dollar match before line breaks (i.e. at the end of a line in a file) as well. Also matches before the very last line break if the string ends with a line break.

Since it's a special/reserved character, it needs to be escaped.

http://www.regular-expressions.info/reference.html

Sign up to request clarification or add additional context in comments.

5 Comments

I get the compiler warning: Unknown escape sequence '\$'
You have to escape the backslash. Try \\$.
No more warning, but the code is not detecting $john type text
What does the string look like? Just "$john"? Are you getting an error of any sort?
There are no matches, so my matches array is empty.

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.