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!!
$ 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.
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 )
The g flag indicates that the regular expression should be tested against all possible matches in a string.
/^([+]\d{2})? \d{10}$/ This is how this regex for mobile number is working. + sign is used for world wide matching of number.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With