问题
I have an NSString I would like to test with an NSRegularExpression, but it doesn't act anything like I would expect and I don't know where to search for an answer anymore.
So here is my code:
BOOL companyNameContainsOnlyAuthorizedCharacters = YES;
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\P{Letter}]" options:0 error:&error];
NSArray *matches = [[NSArray alloc] init];
matches = [regex matchesInString:[model editorName] options:0 range:NSMakeRange(0,[[model editorName] length])];
if ([matches count] > 0) {
companyNameContainsOnlyAuthorizedCharacters = NO;
}
For what I know, [\P{Letter}] should match anything but letters. Nonetheless, instead of that, it just match the characters "\", "P", "{", "L", "e", "t", "r" and "}". I have also tried without the brackets [], but then it doesn't match anything at all.
Any help would be greatly appreciate, thank you in advance.
Edit: Also, xcode gives me a warning that \P is an unknown escape sequence...
回答1:
You need two backslashes:
regularExpressionWithPattern:@"[\\P{Letter}]"
because the backslash itself needs to be escaped in a string.
A perhaps simpler solution to check for "letters only" is
NSString *stringToTest = ...;
NSCharacterSet *letterCharset = [NSCharacterSet letterCharacterSet];
BOOL lettersOnly = [[stringToTest stringByTrimmingCharactersInSet:letterCharset] length] == 0;
回答2:
You need two backslashes. Also, you do not need to enclose this in pattern brackets.
regularExpressionWithPattern:@"\\P{Letter}"
来源:https://stackoverflow.com/questions/15429798/pletter-and-nsregularexpression