1

これが私のコードです:

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)を返します。なぜですか?'<'と'>'の間の文字('<'と'>'を含む)を単にスペースで置き換えたいのです。

4

1 に答える 1

3

regexこれは、で自動解放されたオブジェクトを割り当てているという事実と関係があると思いますviewDidLoad。を追加するか、行をメソッドretainに移動してみてください。findWord

正規表現

<との間のすべてを照合するための正規表現>が正しくありません。正しい方法は、

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:@" "];
于 2011-06-27T13:21:25.563 に答える