简体   繁体   English

正则表达式-仅匹配数字,不包括特殊字符-不起作用

[英]Regex - matching only digits, excluding special characters - doesn't work

I am trying out reggae and was trying to remove the special characters like parentheses, brackets etc. from a phone number. 我正在尝试雷鬼演奏,并试图从电话号码中删除括号,方括号等特殊字符。 Instead of getting the first 3 digits (which I intended), I am getting this [ '201', index: 0, input: '2014447777' ] Why is this happening? 我没有得到前3位数字(这是我想要的),而是得到了这个['201',索引:0,输入:'2014447777']为什么会这样?

 function numbers(num){
 return num.replace(/[^0-9]/g, "").match(/\d\d\d/);

}
numbers("(347)4448888");

String#match returns String#match返回

An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches. 包含整个匹配结果和任何用括号捕获的匹配结果的Array;如果没有匹配项,则为null。

To get first three digits, use 要获得前三位数,请使用

return num.replace(/\D+/g, '').match(/\d{3}/)[0];
                    ^^^               ^^^^^  ^^^   : Match all non-digits
                                      ^^^^^  ^^^   : Match three digits and returns digits from the array.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM