Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 503
Vamshi Gudipati Avatar asked Nov 09 '16 16:11

Vamshi Gudipati


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

How do you validate a country code?

Validates whether the input is a country code in ISO 3166-1 standard. This rule supports the three sets of country codes: ISO 3166-1 alpha-2 ( 'alpha-2' or CountryCode::ALPHA2 )

What is global match in regex?

The g flag indicates that the regular expression should be tested against all possible matches in a string.

How can I check mobile number in regex?

/^([+]\d{2})? \d{10}$/ This is how this regex for mobile number is working. + sign is used for world wide matching of number.


2 Answers

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"
like image 101
Nick G Avatar answered Sep 19 '22 14:09

Nick G


You need to make a case differentiation. Either with or without leading plus sign:

(\+\d{1-3})|(\d{1,4})

Whether you want to anchor the expression to line limits (^ and $) or check for leading or trailing white spaces or the like obviously depends on your situation.

like image 31
arkascha Avatar answered Sep 17 '22 14:09

arkascha