简体   繁体   中英

Regex that validate for a number with length 8, 11, 13 followed by an optional + symbol

I have following regex

^\+?[0-9]*$

I want to validate for a number with length 8, 11, 13 followed by an optional + symbol but don't know how to add lengths 8,11,13 in it.

If + symbol is included the length of whole string must be 8,11 or 13

You regex matches an optional plus sign and a digit [0-9] repeated zero or more times using the asterix * . The regex could also match an empty string or +1

You could use a quantifier like {8} , {11} and {13} .

^(?:\\+(?:[0-9]{12}|[0-9]{10}|[0-9]{7})|(?:[0-9]{13}|[0-9]{11}|[0-9]{8}))$

Match either a plus sign + followed by the digits with the quantifiers for {12} , {10} and {8} .

Or match the digits using a quantifier for {13} , {11} and {9}

You could use double conditionnal :
^\\+[0-9]{8}([0-9]{3}[0-9]{2}?)?$

Explanation :

^ Start of the string
\\+ escaped + symbol
[0-9]{8} It will go for 8 digit,
([0-9]{3} then 3 more digits
[0-9]{2} then 2 more digits
?) which is optionnal
? the whole part after 8 digits is also optionnal
$ end of the string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM