Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何用目标C中的给定字符串替换正则表达式的组1_Ios_Objective C_Regex - Fatal编程技术网

Ios 如何用目标C中的给定字符串替换正则表达式的组1

Ios 如何用目标C中的给定字符串替换正则表达式的组1,ios,objective-c,regex,Ios,Objective C,Regex,我有下面的正则表达式 regex = [NSRegularExpression regularExpressionWithPattern:@"(.*)|(.*)" options:NSRegularExpressionCaseInsensitive error:&error]; 我想用

我有下面的正则表达式

regex = [NSRegularExpression regularExpressionWithPattern:@"(.*)|(.*)"
                                                  options:NSRegularExpressionCaseInsensitive
                                                    error:&error];
我想用文本字段中的值替换与此正则表达式匹配的字符串的第一组

例如,如果我有
Hi|Peter
并替换为
bye
我得到
bye|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
指的是第二个捕获组。请注意,您已经
转义正则表达式中的“|”字符。

这就是您要寻找的吗

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
指的是第二个捕获组。请注意,您已经
转义正则表达式中的“|”字符。

我想就是这个了。非常感谢。我将尝试一下,然后回来将您的答案标记为正确答案。我对模板进行了更改,以适应textfield
withTemplate:[NSString stringWithFormat:@“$1 |%@”,textfield.text]]中的值
@TiagoVeloso:那么现在您保留第一个捕获组并替换第二个组?我有两个文本字段,每个字段编辑正则表达式的一部分。我想我粘贴了我编辑第二组的部分。抱歉给你带来困惑,抱歉耽误了这么长时间。顺便说一句,它起作用了。非常感谢。我想就是这个了。非常感谢。我将尝试一下,然后回来将您的答案标记为正确答案。我对模板进行了更改,以适应textfield
withTemplate:[NSString stringWithFormat:@“$1 |%@”,textfield.text]]中的值
@TiagoVeloso:那么现在您保留第一个捕获组并替换第二个组?我有两个文本字段,每个字段编辑正则表达式的一部分。我想我粘贴了我编辑第二组的部分。抱歉给你带来困惑,抱歉耽误了这么长时间。顺便说一句,它起作用了。非常感谢。