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:@"##(.*)开发者_JS百科$$" options:NSRegularExpressionCaseInsensitive error:nil];
This completely ignores $$
and returns stuff starting with ##
. What am I doing wrong? thanks.
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.
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)];
精彩评论