Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  73] [ 5]  / answers: 1 / hits: 32607  / 8 Years ago, wed, november 9, 2016, 12:00:00

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!!


More From » regex

 Answers
2

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

[#60121] Tuesday, November 8, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaylynbrynnk

Total Points: 706
Total Questions: 98
Total Answers: 91

Location: Israel
Member since Thu, Jan 7, 2021
3 Years ago
;