I use the following regular expression:
NSString *reg1 = @"/[$|§|%|&|{|}|'|`|´|^|°|~]/i";
NSPredicate *messageTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",
reg1];
And I test if the string matches this regex:
if([messageTest evaluateWithObject:message] == NO){
messageValid = NO;
NSLog(@"message invalid");
}
So if the text contains any of the characters that are specified in the regular expression the text is invalid.
This regex worked for me in javascript. However in objective-c I get always NO regardless of what characters are in the string.
Where is the problem?
There are essentially two problems with your code. Firstly, your regular expression
is wrong:
${}^|to separate characters in a character class.The ICU regular expression you want is
Try this in your program:
(note that the
\character is represented as\\in an Objective-C string.)Secondly, you’re testing
to check whether a message is invalid. But
-evaluateWithObject:returningNOmeans that there wasn’t a match, hence the string doesn’t contain any of those characters, hence the string is valid. You need to change that to its opposite, namely:which means that there was a match, hence the string contain at least one of those characters, hence the string isn’t valid.