Why is my NSRegularExpression pattern not working?

橙三吉。 提交于 2019-12-13 04:40:58

问题


I have the following string:

NSString *string = @"she seemed \x3cem\x3ereluctant\x3c/em\x3e to discuss the matter";

I want the final string to be: "she seemed reluctant to discuss the matter"

I have the following pattern:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"/\\x[0-9a-f]{2}/"
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];

NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
    NSRange matchRange = [match range];
    NSLog(@"%@", NSStringFromRange(matchRange));
}

However, I get an error saying the pattern is invalid. What am I doing wrong?


回答1:


The pattern you need is:

@"\\\\x[0-9a-f]{2}"

The backslash is special to both Obj-C and the RE parser - so you need to create an Obj-C string with two \'s so the RE parser can then end up with one.

Also there are no open/close delimiters in the string - you're thinking of another programming language there!




回答2:


You can save yourself some regex troubles by using the NSString method

stringByReplacingOccurrencesOfString:withString:

Or

stringByReplacingOccurrencesOfString:withString:options:range:



来源:https://stackoverflow.com/questions/20414673/why-is-my-nsregularexpression-pattern-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!