逃避正则表达式保留字符?

时间:2015-12-29 01:45:51

标签: ios objective-c regex

任何人都知道如何从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:@"\\/"];

但这太贵了。

感谢。

2 个答案:

答案 0 :(得分:1)

因此,对于那些想要一种简单方法的人,您可以查看NSRegularExpression课程here

在那里你会找到一些方法来做到这一点,其中之一就是:

+ escapedTemplateForString:

答案 1 :(得分:0)

Swift 3/4 使用:

let escapedStr = NSRegularExpression.escapedPattern(for: myString)

<强>结果:

myString = "Hello (world)"
escapedStr = "Hello \\(world\\)"

完美无缺!