【问题标题】:Objective-c Regex errorObjective-c 正则表达式错误
【发布时间】:2016-02-05 00:50:47
【问题描述】:

我有这个字符串:

{{nat fs g player|no=1|pos=GK|name=[[Hugo Lloris]]|age={{Birth date and age|1986|12|26|df=y}}|caps=73|goals=0|club=[[Tottenham Hotspur F.C.|Tottenham Hotspur]]|clubnat=ENG}}

我想从这个字符串中获取数据,所以我构建了正则表达式:

https://regex101.com/r/jA1zS4/1

但是当我在我的项目中运行这段代码时,我得到了错误:

NSString *string = @"{{nat fs g player|no=1|pos=GK|name=[[Hugo Lloris]]|age={{Birth date and age|1986|12|26|df=y}}|caps=73|goals=0|club=[[Tottenham Hotspur F.C.|Tottenham Hotspur]]|clubnat=ENG}}";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"{{nat fs g player\\|no=(.*)\\|pos=(.*?)\\|name=\[\[(.*?)\\]\\]\\|age=\{\{Birth date and age\\|(.*?)\\|(.*?)\\|(.*?)\\|df=y\\}\\}\\|caps=(.*?)\\|goals=(.*?)\\|club=\[\[(.*?)\\|(.*)"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];

NSArray *matches = [regex matchesInString:string
                                  options:0
                                    range:NSMakeRange(0, [string length])];


Error Domain=NSCocoaErrorDomain Code=2048 "The value “{{nat fs g player\|no=(.*)\|pos=(.*?)\|name=[[(.*?)\]\]\|age={{Birth date and age\|(.*?)\|(.*?)\|(.*?)\|df=y\}\}\|caps=(.*?)\|goals=(.*?)\|club=[[(.*?)\|(.*)” is invalid." UserInfo={NSInvalidValue={{nat fs g player\|no=(.*)\|pos=(.*?)\|name=[[(.*?)\]\]\|age={{Birth date and age\|(.*?)\|(.*?)\|(.*?)\|df=y\}\}\|caps=(.*?)\|goals=(.*?)\|club=[[(.*?)\|(.*)}

【问题讨论】:

  • 您未能正确转义方括号。

标签: ios objective-c iphone regex nsregularexpression


【解决方案1】:

我会使用一些不同的正则表达式:我会将所有 .*? 替换为 [^|]* 以获得更好的性能:

\{\{nat fs g player\|no=([^|]*)\|pos=([^|]*)\|name=\[\[([^|]*)\]\]\|age=\{\{Birth date and age\|([^|]*)\|([^|]*)\|([^|]*)\|df=y}}\|caps=([^|]*)\|goals=([^|]*)\|club=\[\[([^|]*)\|(.*)

而在Objective-C中,你需要转义所有|[]{}

NSString *pattern = @"\\{\\{nat fs g player\\|no=([^|]*)\\|pos=([^|]*)\\|name=\\[\\[([^|]*)\\]\\]\\|age=\\{\\{Birth date and age\\|([^|]*)\\|([^|]*)\\|([^|]*)\\|df=y\\}\\}\\|caps=([^|]*)\\|goals=([^|]*)\\|club=\\[\\[([^|]*)\\|(.*)";

查看IDEONE demo 证明存在匹配。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    相关资源
    最近更新 更多