Anyone know how to escape reserved regex's characters from a NSString?
I think these are the special characters that I must escape
. ^ $ * + - ? ( ) [ ] { } \ |
Currently I'm using this to escape all characters:
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:@"\\/"];
but that's too expensive.
Thanks.
So, for those who want a simple way to do this you can check NSRegularExpression
class here
There you'll find some methods to do this, one of them is:
+ escapedTemplateForString:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments