【问题标题】:NSRegularExpression weird behaviourNSRegularExpression 奇怪的行为
【发布时间】:2014-02-04 02:35:44
【问题描述】:

我已经尝试了几个小时,但在互联网上找不到类似的东西,所以希望你能帮助我..

我正在尝试替换 NSString 中的单个字符,应该很简单吧? 这是我所做的:

NSError *error;
NSString *str1 = @"E bis the EVE E on E is the  the hte ee e.";
NSString *str2 = @"E abis the EVE E on E is the  the hte ee e.";

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\bE\\b"
                                                       options:NSRegularExpressionCaseInsensitive
                                                       error:&error];


int numberOfMatches1 = [regex numberOfMatchesInString:str1
                                               options:0
                                               range:NSMakeRange(0, [str1 length])];
int numberOfMatches2 = [regex numberOfMatchesInString:str2
                                               options:0
                                               range:NSMakeRange(0, [str2 length])];
NSLog(@"%d, %d",numberOfMatches1,numberOfMatches2);

NSString *modifiedStr1 = [regex stringByReplacingMatchesInString:str1
                                               options:0
                                               range:NSMakeRange(0, [str1 length])
                                               withTemplate:@"O"];

NSString *modifiedStr2 = [regex stringByReplacingMatchesInString:str2
                                               options:0
                                               range:NSMakeRange(0, [str2 length])
                                               withTemplate:@"O"];

NSLog(modifiedStr1);
NSLog(modifiedStr2);

我们的想法是用 O 替换所有单个 E(也位于字符串的开头和结尾),并保留所有其他 E。 在第一个字符串中,这按预期工作,但是当我在字符串中添加一些东西时,在这种情况下,第二个位置的“a”会出现误报。 输出是:

4, 5 (str1 和 str2 匹配的 Nr)

O bis the EVE O on O 是hte ee O。

O abis the EVE O on O is the thO hte ee O.

我做错了什么?

【问题讨论】:

    标签: objective-c regex nsregularexpression


    【解决方案1】:

    除了编译器警告 - 你的两个 int 应该是 NSUInteger,这又需要格式字符串中的 %lu,最后两个 NSLog 调用应该有一个格式字符串 - 你是在您显示的代码中没有做错任何事情,它按预期工作(在 10.8.5 上使用 Xcode 5.0.2 测试)。

    所以你的问题在别处。单步调试调试器中的代码,记下所有指针值等,希望您能找到它。

    【讨论】:

    • 感谢 CRD 的指点。这是在 Linux 上使用 GNUStep 完成的。我现在在 XCode 中尝试了它,一切都按预期工作......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2015-07-20
    • 2010-10-03
    • 2021-07-12
    相关资源
    最近更新 更多