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