stringByReplacingMatchesInString:返回(空)
这是我的代码:
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)。为什么?我想替换“<”之间的任何字符和“>”包括“<”和“>”只需一个空格即可。
Here is my code:
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);
}
My 'modifiedString' is returning (null).Why?I want to replace any characters between '<' and '>' including '<' and '>' simply by a space.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜这与您在
viewDidLoad
中将自动释放的对象分配给regex
的事实有很大关系。尝试添加retain
或将该行移至findWord
方法。正则表达式
用于匹配
<
和>
之间所有内容的正则表达式不正确。正确的方法是,用空格替换
如果您想用
" "
替换匹配的字符串,那么您不应该将$1
作为模板传递。相反,使用" "
作为模板。I am guessing this has a lot to do with the fact that you are assigning an autoreleased object to
regex
inviewDidLoad
. Try adding aretain
or move the line to thefindWord
method.Regex
The regular expression for matching everything between
<
and>
is incorrect. The correct way would be,Replace by space
If you want to replace the matched string with
" "
then you shouldn't pass$1
as the template. Rather, use" "
as the template.