ios - "\P{Letter}"和 NSRegularExpression

标签 ios objective-c regex xcode nsregularexpression

我有一个 NSString,我想用 NSRegularExpression 进行测试,但它的行为与我预期的不一样,而且我不知道在哪里再搜索答案。

这是我的代码:

    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;

    }

据我所知, [\P{Letter}] 应该匹配除字母之外的任何内容。尽管如此,它只是匹配字符“\”、“P”、“{”、“L”、“e”、“t”、“r”和“}”。我也尝试过不使用方括号 [],但它根本不匹配任何内容。

任何帮助将不胜感激,提前谢谢您。

编辑: 另外,xcode 给我一个警告,\P 是一个未知的转义序列...

最佳答案

您需要两个反斜杠:

regularExpressionWithPattern:@"[\\P{Letter}]"

因为反斜杠本身需要在字符串中转义。

检查“仅字母”的可能更简单的解决方案是

NSString *stringToTest = ...;
NSCharacterSet *letterCharset = [NSCharacterSet letterCharacterSet];
BOOL lettersOnly = [[stringToTest stringByTrimmingCharactersInSet:letterCharset] length] == 0;

关于ios - "\P{Letter}"和 NSRegularExpression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15429798/

相关文章:

ios - 为什么整个单词的 sizeWithFont 不同于其字母大小的总和?

ios - UIAlertAction 没有初始化程序(标题、样式、处理程序)

ios - 将 Storyboard或 xib 用于单 View Controller ?

iphone - block 而不是 performSelector :withObject:afterDelay:

objective-c - 登录 View 之前的模态视图屏幕

ios - 按值传递的结构参数包含未初始化的数据

javascript - 将文本 url 链接转换为可点击的链接

c# - Regex.Match 在 C# 中的双辅音

iOS iTunes 无法删除设备 : An unspecified error occurred. 请刷新并重试

java - 使用正则表达式从字符串中提取数字