Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

javascript - Regex for country code

I'm trying to write a regex for country code, which should limit to four characters maximum, only symbol allowed is a + sign. When the + is used, the + has to be in the beginning, and it should have at least one number.

Valid cases

+1
1
+12
12
+123
1234

Invalid cases

+
+1234
12345
1+
12+
<empty>
etc.

The expression that I have right now.

/(+d{1,3})/

Can it be more elegant?

-Thank you in advance!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This should work. I used

/^(+?d{1,3}|d{1,4})$/

See results

Edit:

The //gm flags are global and multiline, respectively. You need those if you have a string that can have multiple places to match a country code, or there are multiple lines in your string. If your string is going to be more than just a possible country code, you'd need to get rid of the ^ and $ at the beginning and end of the regex. To use the regex, you'd want something like this:

var regex = /^(+?d{1,3}|d{1,4})$/gm
var str = "+123"
var match = str.match(regex);
//match is an array, with one result in this case. So match[0] == "+123"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...