正则表达式(replaceMatchesInString)不起作用 [英] RegEx (replaceMatchesInString) does not work

查看:101
本文介绍了正则表达式(replaceMatchesInString)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个带有 replaceMatchesInString 的 RegEx 只返回+"而不是+123"?

Why does this RegEx with replaceMatchesInString return only "+" instead of "+123"?

NString *phoneNumberCleaned = [NSString stringWithFormat:@"++00123"];

NSString *strRegExPhoneNumberPrefixWrong = @"^([+0]*)\\d*$";

NSRegularExpression *regEx = [NSRegularExpression regularExpressionWithPattern:strRegEx options:0 error:nil];

[regEx replaceMatchesInString:phoneNumberCleaned options:0 range:NSMakeRange(0, [phoneNumberCleaned length]) withTemplate:@"+"];

return phoneNumberCleaned;

谢谢

推荐答案

NSString *string = @"++00123";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression 
   regularExpressionWithPattern:@"^[+0]+(?=\\d*)" 
                         options:NSRegularExpressionCaseInsensitive 
                           error:&error];

NSString *modifiedString = [regex 
           stringByReplacingMatchesInString:string 
                                    options:0 
                                      range:NSMakeRange(0, [string length]) 
                               withTemplate:@"+"];
return modifiedString;

你的正则表达式的问题是 ^([+0]*)\\d*$ 也匹配 \d* 这意味着,它也被替换(您认为它只会替换您的捕获组,但显然事实并非如此).因此,您实际上是在替换与上述模式匹配的任何字符串(包括任何尾随数字),在您的情况下是整个数字.

The problem with your Regex was that ^([+0]*)\\d*$ is also matching the \d* which means, that it also gets replaced (you'd think that it would only replace your capture group, but evidently that isn't so). So you were essentialy replacing any string that matches the above pattern (which was including any trailing numbers), which in your case was the entire number.

我在回答中使用的称为 positive lookahead.

What I used in my answer is called a positive lookahead.

^[+0]+(?=\\d*)$

前瞻基本上意味着您正在寻找零个或多个 +0 后跟零个或多个数字,不包括匹配中的数字.所以你只替换零和加号,而不是它们后面的数字.

The lookahead basically means that you're looking for zero or more + or 0 that are followed by zero or more digits EXCLUDING the digits from the match. So you only replace the zeroes and pluses, not the digits following them.

这篇关于正则表达式(replaceMatchesInString)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆