ios - 如何在 objective-c 中用给定的字符串替换正则表达式的组1

标签 ios objective-c regex

我有以下正则表达式

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/

相关文章:

android - 在 Cordova 中开发网站应用程序的正确方法是什么?

objective-c - 异步获取大量资源并将其保存到数据库 "asynchronously"使用哪种好的模式? (AFNetworking,核心数据)

regex - 如何制作一个正则表达式来匹配模式之间带有随机点的字符串?

regex - Shell 正则表达式到行尾

ios - 重新加载数据时刷新 tableView 闪烁

objective-c - 来自委托(delegate)的 shouldAutorotateToInterfaceOrientation

ios - 谷歌分析 : Several Questions about deployment

ios - Storyboard似乎未正确加载

ios - 在方法上使用未声明的标识符

python - 正则表达式帮助将列表拆分为二元组