有人知道如何从NSString中转义保留的正则表达式字符吗?
我认为这些是我必须逃避的特殊字符
. ^ $ * + - ? ( ) [ ] { } \ |
目前,我正在使用它来转义所有字符:
regex = [regex stringByReplacingOccurrencesOfString: @"\\" withString:@"\\\\"];
regex = [regex stringByReplacingOccurrencesOfString: @"{" withString:@"\\{"];
regex = [regex stringByReplacingOccurrencesOfString: @"}" withString:@"\\}"];
regex = [regex stringByReplacingOccurrencesOfString: @"?" withString:@"\\?"];
regex = [regex stringByReplacingOccurrencesOfString: @"+" withString:@"\\+"];
regex = [regex stringByReplacingOccurrencesOfString: @"[" withString:@"\\["];
regex = [regex stringByReplacingOccurrencesOfString: @"(" withString:@"\\("];
regex = [regex stringByReplacingOccurrencesOfString: @")" withString:@"\\)"];
regex = [regex stringByReplacingOccurrencesOfString: @"^" withString:@"\\^"];
regex = [regex stringByReplacingOccurrencesOfString: @"$" withString:@"\\$"];
regex = [regex stringByReplacingOccurrencesOfString: @"|" withString:@"\\|"];
regex = [regex stringByReplacingOccurrencesOfString: @"/" withString:@"\\/"];
但这太贵了。
谢谢。
因此,对于那些想要一种简单方法的人,可以在这里查看NSRegularExpression
课程
在那里,您会找到一些方法来执行此操作,其中一种是:
+ escapedTemplateForString:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句