sumderungHAY
sumderungHAY

Reputation: 1337

NSRegularExpression string delimited by

I have a string for example @"You've earned Commentator and 4 ##other$$ badges". I want to retreive the substring @"other", which is delimited by ## and $$. I made a NSRegularExpression like this:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"##(.*)$$" options:NSRegularExpressionCaseInsensitive error:nil];

This completely ignores $$ and returns stuff starting with ##. What am I doing wrong? thanks.

Upvotes: 1

Views: 957

Answers (2)

NSResponder
NSResponder

Reputation: 16861

I wouldn't use a regex in this situation, since the string bashing is so simple. No need for the overhead of compiling the expression.

NSString *source = @"You've earned Commentator and 4 ##other$$ badges";
NSRange firstDelimiterRange = [source rangeOfString:@"##"];
NSRange secondDelimiterRange = [source rangeOfString:@"$$"];
NSString *result = [source substringWithRange:
  NSMakeRange(firstDelimiterRange.origin +2, 
    firstDelimiterRange.origin - secondDelimiterRange.origin)];

Upvotes: 1

drekka
drekka

Reputation: 21883

Thats because '$' is a special character that represents the end of the line. Try \$\$ to escape it and tell the parser you want the characters.

Upvotes: 1

Related Questions