Regex for country code

前端 未结 4 1326
日久生厌
日久生厌 2020-12-20 21:12

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 beg

相关标签:
4条回答
  • 2020-12-20 21:54

    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.

    0 讨论(0)
  • 2020-12-20 21:54

    country codes can be of following types

    • +1
    • +91
    • +223
    • +1-224

    The javascript regex that makes sure that the input is one if the

    /^\+(\d{1}\-)?(\d{1,3})$/
    
    0 讨论(0)
  • 2020-12-20 22:02

    I prepared this according to wikipedia article, for parsing correct information for 1 or 2 digit country codes this is much more efficient, but needs improvement for subterritories if you need them;

    (?:\+|00)(1|7|2[07]|3[0123469]|4[013456789]|5[12345678]|6[0123456]|8[1246]|9[0123458]|(?:2[12345689]|3[578]|42|5[09]|6[789]|8[035789]|9[679])\d)
    
    0 讨论(0)
  • 2020-12-20 22:11

    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"
    
    0 讨论(0)
提交回复
热议问题