Ios 转义正则表达式保留字符?
有人知道如何从NSString中转义保留正则表达式的字符吗 我想这些是我必须摆脱的特殊角色Ios 转义正则表达式保留字符?,ios,objective-c,regex,Ios,Objective C,Regex,有人知道如何从NSString中转义保留正则表达式的字符吗 我想这些是我必须摆脱的特殊角色 . ^ $ * + - ? ( ) [ ] { } \ | 目前,我正在使用它来转义所有字符: regex = [regex stringByReplacingOccurrencesOfString: @"\\" withString:@"\\\\"]; regex = [regex stringByReplacingOccurrencesOfString: @"{" withStrin
. ^ $ * + - ? ( ) [ ] { } \ |
目前,我正在使用它来转义所有字符:
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:
对于Swift 3/4使用:
let escapedStr = NSRegularExpression.escapedPattern(for: myString)
结果:
myString = "Hello (world)"
escapedStr = "Hello \\(world\\)"
很好用