我有以下正则表达式
regex = [NSRegularExpression regularExpressionWithPattern:@"(.*)|(.*)"
options:NSRegularExpressionCaseInsensitive
error:&error];
我想用文本字段中的值替换匹配此正则表达式的字符串的第一组。
例如,如果我有
Hi|Peter
并替换为Goodbye
,我会得到Goodbye|Peter
我怎样才能做到这一点?
最佳答案
这是你想要的?
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
引用第二个捕获组。注意你有逃脱“|”正则表达式中的字符。
关于ios - 如何在 objective-c 中用给定的字符串替换正则表达式的组1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15944733/