我需要用一种特定的方式格式化我的电话号码。不幸的是,商业规则禁止我提前做这件事。(单独的输入框等)
格式需要是+1-xxx-xxx-xxxx,其中"+1“是常量。(我们在国际上不做生意)
下面是测试输入的regex模式:
"\\D*([2-9]\\d{2})(\\D*)([2-9]\\d{2})(\\D*)(\\d{4})\\D*"(这是我从其他地方偷来的)
然后执行regex.Replace(),如下所示:
regex.Replace(telephoneNumber, "+1-$1-$3-$5"); **THIS IS WHERE IT BLOWS UP**如果我的电话号码在字符串中已经有"+1“,它会加上另一个,这样我就可以得到+1-+1-xxx-xxx-xxxx。
有人能帮忙吗?
发布于 2015-07-09 17:33:20
您可以添加(?:\+1\D*)?以在数字之前捕获一个可选前缀。当它被抓住时,如果它在那里,它就会被替换。
您不需要在号码前后使用\D*。因为它们是可选的,所以它们不会改变任何东西。
您不需要捕获您不使用的部件,这样就可以更容易地看到替换后的结果。
str = Regex.Replace(str, @"(?:\+1\D*)?([2-9]\d{2})\D*([2-9]\d{2})\D*(\d{4})", "+1-$1-$2-$3");不过,您可以考虑在分隔符中使用比\D*更具体的内容,例如[\- /]?。使用过于非特定的模式,您可能会发现一些不是电话号码的东西,例如将"I have 234 cats, 528 dogs and 4509 horses."转换为"I have +1-234-528-4509 horses."。
str = Regex.Replace(str, @"(?:\+1[\- /]?)?([2-9]\d{2})[\- /]?([2-9]\d{2})[\- /]?(\d{4})", "+1-$1-$2-$3");发布于 2015-07-09 17:51:16
尝试像这样的东西来使事物更易读:
Regex rxPhoneNumber = new Regex( @"
^ # anchor the start-of-match to start-of-text
\D* # - allow and ignore any leading non-digits
1? # - we'll allow (and ignore) a leading 1 (as in 1-800-123-4567
\D* # - allow and ignore any non-digits following that
(?<areaCode>[2-9]\d\d) # - required 3-digit area code
\D* # - allow and ignore any non-digits following the area code
(?<exchangeCode>[2-9]\d\d) # - required 3-digit exchange code (central office)
\D* # - allow and ignore any non-digits following the C.O.
(?<subscriberNumber>\d\d\d\d) # - required 4-digit subscriber number
\D* # - allow and ignore any non-digits following the subscriber number
$ # - followed the end-of-text.
" ,
RegexOptions.IgnorePatternWhitespace|RegexOptions.ExplicitCapture
);
string input = "voice: 1 (234) 567/1234 (leave a message)" ;
bool isValid = rxPhoneNumber.IsMatch(input) ;
string tidied = rxPhoneNumber.Replace( input , "+1-${areaCode}-${exchangeCode}-${subscriberNumber}" ) ;,这将为tidied提供所需的值。
+1-234-567-1234发布于 2015-07-09 17:27:19
您可以使用以下正则表达式
\D*(\+1-)?([2-9]\d{2})\D*([2-9]\d{2})\D*(\d{4})\D*和替换字符串:
$1$2-$3-$4这是一个演示
这是对你所拥有的正则表达式的调整。如果你需要匹配所有的数字,我会用
(\+1-)?\b([2-9]\d{2})\D*([2-9]\d{2})\D*(\d{4})\b请参阅演示2

另外,如果\+1-中的连字符是可选的,则添加一个?:\+1-?。
为了使正则表达式更安全,我将\D* (0或更多的非数字符号)替换为包含已知分隔符的字符类,例如[ /-]* (匹配/、空格和-s)。
https://stackoverflow.com/questions/31324230
复制相似问题