【问题标题】:Objective-c NSRegularExpression strange matchObjective-c NSRegularExpression 奇怪的匹配
【发布时间】:2015-09-30 05:26:41
【问题描述】:

我的 NSString 模式效果不佳。

NSString *pattern = @"/api/v1/news/([0-9]+)/\\?categoryId=([0-9]+)";
NSString *string = urlString;
NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:pattern
                              options:NSRegularExpressionCaseInsensitive
                              error:nil];

为什么它也匹配下面的字符串?

/api/v1/news/123/?categoryId=22abc

我只想匹配

/api/v1/news/123/?categoryId=22

其中 123 和 22 可以是可变数字。

【问题讨论】:

  • 显示其余代码,您可以在其中访问NSTextCheckingResult
  • 在末尾加上 \b 或 $ 以确保路径以一位或多位数字结尾。
  • ICU 用户指南:Regular Expressions

标签: objective-c regex nsregularexpression


【解决方案1】:

您的正则表达式很好,但它允许部分匹配。要禁止它们,请使用 ^$ 锚点:

^/api/v1/news/([0-9]+)/\\?categoryId=([0-9]+)$
^                                            ^

regex demo

^ 断言字符串开头的位置,$ 断言字符串末尾的位置。

另请参阅 IDEONE demo 显示 NO MATCH 用于您拥有的第一个输入字符串,this demo 匹配第二个。

如果您需要将这些字符串作为单独的单词进行匹配,请在末尾使用\\b(单词边界)并在开头使用(?<!\\w)look-behind(确保之前没有单词字符):

(?<!\\w)/api/v1/news/([0-9]+)/\\?categoryId=([0-9]+)\\b
^^^^^^^^                                             ^^

如果您还需要访问捕获的文本,请使用以下内容:

NSString *pattern = @"^/api/v1/news/([0-9]+)/\\?categoryId=([0-9]+)$";
NSString *string = @"/api/v1/news/123/?categoryId=22";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:string 
                            options:0 
                            range:NSMakeRange(0, string.length)];
NSLog(@"Group 1 number: %@", [string substringWithRange:[match rangeAtIndex:1]]);
NSLog(@"Group 2 number: %@", [string substringWithRange:[match rangeAtIndex:2]]);

IDEONE demo,输出为

Group 1 number: 123
Group 2 number: 22

【讨论】:

    猜你喜欢
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 2013-11-09
    相关资源
    最近更新 更多