“\P{Letter}” and NSRegularExpression

浪尽此生 提交于 2019-12-11 19:13:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!