【问题标题】:stringByReplacingMatchesInString: returns (null)stringByReplacingMatchesInString:返回(空)
【发布时间】:2011-09-23 12:20:32
【问题描述】:

这是我的代码:

NSRegularExpression * regex;

- (void)viewDidLoad {
    NSError *error = NULL;
    regex = [NSRegularExpression regularExpressionWithPattern:@"<*>" options:NSRegularExpressionCaseInsensitive error:&error];
}

- (IBAction)findWord {  
    NSString * fileContents=[NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@/report1_index1_page1.html", [[NSBundle mainBundle] resourcePath]]];
    NSLog(@"%@",fileContents);

    NSString * modifiedString = [regex stringByReplacingMatchesInString:fileContents
                                                                options:0
                                                                  range:NSMakeRange(0, [fileContents length])
                                                           withTemplate:@"$1"];

    NSLog(@"%@",modifiedString);
}

我的 'modifiedString' 正在返回 (null)。为什么?我想用空格替换 '' 之间的任何字符,包括 ''。

【问题讨论】:

    标签: iphone objective-c regex ios4 nsregularexpression


    【解决方案1】:

    我猜这与您在viewDidLoad 中将自动释放的对象分配给regex 的事实有很大关系。尝试添加retain 或将行移至findWord 方法。

    正则表达式

    匹配&lt;&gt; 之间所有内容的正则表达式不正确。正确的做法是,

    NSError *error = nil;
    NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=<).*(?=>)" options:NSRegularExpressionCaseInsensitive error:&error];
    if ( error ) {
        NSLog(@"%@", error);
    }
    

    用空格替换

    如果您想用" " 替换匹配的字符串,那么您不应该将$1 作为模板传递。而是使用" " 作为模板。

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

    【讨论】:

    • 我的正则表达式或声明方法有什么错误吗?我不确定。
    • 您仍然得到null 还是没有得到想要的结果?如果是这样,您可以NSLog(@"%@", regex); 告诉我它打印的内容吗?
    • @Deepak:NSLog(@"%@", 正则表达式);也打印 (null)
    • viewDidLoad 中是否也这样做?您可能想检查error 是否不是nil,然后也将其记录下来。如果regexviewDidLoad 中不是nil,那么在findWord 中添加该代码时会发生什么?
    • @Deepak:真的很混乱。在 viewDidLoad 中,正则表达式也来了(null),错误也来了(null)。这里做错了什么?
    猜你喜欢
    • 2013-05-04
    • 2012-07-07
    • 2018-12-23
    • 1970-01-01
    • 2021-07-07
    • 2013-09-30
    • 2021-08-23
    • 2013-04-07
    • 2018-05-21
    相关资源
    最近更新 更多