简体   繁体   English

正则表达式从电话号码中提取两位数

[英]Regex to extract two digits from phone number

I am trying to take only 2 characters from my phone no. 我试图从电话号码中仅提取2个字符。 I have used regex match ^\\+55 and this will return the following example. 我使用了正则表达式匹配^\\+55 ,这将返回以下示例。

Phone No : +5546342543 电话号码: +5546342543

Result : 46342543 结果: 46342543

Expected Result was only 46 . 预期结果仅为46

I don't want to use substring for the answer instead I want to extract that from the phone no with regex. 我不想使用子字符串作为答案,而是我想使用正则表达式从电话中提取该字符串。

Can anybody help me on this. 有人可以帮我吗? Thank you. 谢谢。

只需尝试:

'+5546342543'.match(/^\+55(\d{2})/)[1];

The pattern you used - ^\\+55 - matches a literal + in the beginning of the string and two 5 s right after. 您使用的模式- ^\\+55匹配字符串开头的文字+ ,之后匹配两个5 s。

46 is the substring that appears right after the initial +55 . 46是在初始+55之后立即出现的子字符串。 In some languages, you can use a look-behind (see example ) to match some text preceded with another. 在某些语言中,您可以使用后向搜索 (请参见示例 )来匹配某些文本,然后再匹配其他文本。

JavaScript has no look-behind support, so, you need to resort to capturing groups . JavaScript没有后向支持,因此,您需要诉诸捕获组

You can use string#match or RegExp#exec to obtain that captured text marked with round brackets: 您可以使用string#matchRegExp#exec来获取捕获的带有圆括号的文本:

 var s = '+5546342543'; if ((m=/^\\+55(\\d{2})/.exec(s)) !== null) { document.write(m[1]); } 

This example handles the case when you get no match. 本示例处理没有匹配项的情况。

这会得到你想要的

"+5546342543".match(/^\+55(.*)/)[1]

This solves your problem ? 这样可以解决您的问题吗?

phoneNumber = "+5546342543"
phone = phoneNumber.substr(3) // returns "46342543" 
twoDigits = phoneNumber.substr(3,2) // returns "46"

Using the substr() method as quoted : 使用引用的substr()方法:

The substr() method returns the characters in a string beginning at the specified location through the specified number of characters. substr()方法以指定的字符数返回从指定位置开始的字符串中的字符。

Syntax: str.substr(start[, length]) 语法: str.substr(start[, length])

Source : Mozilla MDN 资料来源: Mozilla MDN

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

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