开发者

NSRegularExpression string delimited by

开发者 https://www.devze.com 2023-03-18 10:39 出处:网络
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

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)];
0

精彩评论

暂无评论...
验证码 换一张
取 消