1

次の正規表現があります

regex = [NSRegularExpression regularExpressionWithPattern:@"(.*)|(.*)"
                                                  options:NSRegularExpressionCaseInsensitive
                                                    error:&error];

この正規表現に一致する文字列の最初のグループを、テキスト フィールドの値に置き換えたいと考えています。

たとえば、私が持っていて、次のようHi|Peterに置き換えるとGoodbyeGoodbye|Peter

これどうやってするの?

4

1 に答える 1

8

これはあなたが探しているものですか?

NSString *s1 = @"Hi|Peter";
NSError *error;
NSString *pattern = @"(.*)\\|(.*)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                      options:NSRegularExpressionCaseInsensitive
                                    error:&error];
NSString *s2 = [regex stringByReplacingMatchesInString:s1
                           options:0
                         range:NSMakeRange(0, [s1 length])
                      withTemplate:@"Goodbye|$2"];
NSLog(@"%@", s2);
// Output: Goodbye|Peter

$2置換テンプレートの は、2 番目のキャプチャ グループを指します。「|」をエスケープする必要があることに注意してください 正規表現の文字。

于 2013-04-11T09:59:02.177 に答える