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 'modifiedStri开发者_高级运维ng' is returning (null).Why?I want to replace any characters between '<' and '>' including '<' and '>' simply by a space.
I am guessing this has a lot to do with the fact that you are assigning an autoreleased object to regex
in viewDidLoad
. Try adding a retain
or move the line to the findWord
method.
Regex
The regular expression for matching everything between <
and >
is incorrect. The correct way would be,
NSError *error = nil;
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=<).*(?=>)" options:NSRegularExpressionCaseInsensitive error:&error];
if ( error ) {
NSLog(@"%@", error);
}
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.
NSString * modifiedString = [regex stringByReplacingMatchesInString:fileContents
options:0
range:NSMakeRange(0, [fileContents length])
withTemplate:@" "];
精彩评论