简体   繁体   中英

Regex to extract two digits from phone number

I am trying to take only 2 characters from my phone no. I have used regex match ^\\+55 and this will return the following example.

Phone No : +5546342543

Result : 46342543

Expected Result was only 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.

46 is the substring that appears right after the initial +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 .

You can use string#match or RegExp#exec to obtain that captured text marked with round brackets:

 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 :

The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.

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

Source : Mozilla MDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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