简体   繁体   中英

How to set the minimum and maximum number of digit allowed in a regex expression for telephone number

I have the following Regex expression for java application:

[\+0-9]+([\s0-9]+)?

How to restrict the above expression of telephone number to a minimum of 4 digits and maximum of 7 digits? I thought it would be something like adding this {4,7} to the expression but it is not working.

Any advice please?

Basically my telephone number can either start with a + sign followed with numbers(+004...) or with numbers only(004...) and can also contain white spaces in between any digits(0 0 4...).

You can try this regex:

[+]?(?:[0-9]\s*){4,7}

Explanation:

[+]?           // Optional + sign
(?:[0-9]\s*)   // A single digit followed by 0 or more whitespaces
{4,7}          // 4 to 7 repetition of previous pattern

Sample tests:

String regex = "[+]?(?:[0-9]\\s*){4,7}";

System.out.println("0045234".matches(regex));       // true
System.out.println("+004 5234".matches(regex));      // true
System.out.println("+00 452 34".matches(regex));    // true
System.out.println("0 0 4 5 2 3 4".matches(regex)); // true
System.out.println("004523434534".matches(regex));  // false
System.out.println("004".matches(regex));           // false

"\\\\+?(\\\\d ?){3,6}\\\\d"应该匹配一个可选的+号,后跟4-7个数字以及两个数字之间的可选空格。

Similar structure as above, but with: :? taken off :? taken off (not sure why is it there?)

[+]?([0-9]\s*){4,7}

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