简体   繁体   中英

Length of some characters in regex

I have following regex:

\+?[0-9\.,()\-\s]+$

which allows:

  • optional + at the beginning
  • then numbers, dots, commas, round brackets, dashes and white spaces.

In addition to that I need to make sure that amount of numbers and plus symbol (if exists) has length between 9 and 15 (so I'm not counting any special characters apart from + symbol).

And this last condition is what I'm having problem with.

valid inputs:

  • +358 (9) 1234567
  • +3 5 8.9,1-2(3)4..5,6.7 (25 characters but only 12 characters that counts (numbers and plus symbol))

invalid input:

  • +3 5 8.9,1-2(3)4..5,6.777777777 (33 characters and only 20 characters that counts (numbers and plus symbol) is too many)

It is important to use regex if possible because it's used in javax.validation.constraints.Pattern annotation as:

@Pattern(regexp = REGEX) 
private String number;

where my REGEX is what I'm looking for here.

And if regex cannot be provided then it means that I need to rewrite my entity validation implementation. So is it possible to add such condition to regex or do I need a function to validate such pattern?

You may use

^(?=(?:[^0-9+]*[0-9+]){9,15}[^0-9+]*$)\+?[0-9.,()\s-]+$

See the regex demo

Details

  • ^ - start of string
  • (?=(?:[^0-9+]*[0-9+]){9,15}[^0-9+]*$) - a positive lookahead whose pattern must match for the regex to find a match:

    • (?:[^0-9+]*[0-9+]){9,15} - 9 to 15 repetitions of
    • [^0-9+]* - any 0+ chars other than digits and + symbol
    • [0-9+] - a digit or +
    • [^0-9+]* - 0+ chars other than digits and +
    • $ - end of string
  • \\+? - an optional + symbol

  • [0-9.,()\\s-]+ - 1 or more digits, . , , , ( , ) , whitespace and - chars
  • $ - end of string.

In Java, when used with matches() , the ^ and $ anchors may be omitted:

s.matches("(?=(?:[^0-9+]*[0-9+]){9,15}[^0-9+]*$)\\+?[0-9.,()\\s-]+")

Not using regex, you could simply loop and count the numbers and + s:

int count = 0;
for (int i = 0; i < str.length(); i++) {
    if (Character.isDigit(str.charAt(i)) || str.charAt(i) == '+') {
        count++;
    }
}

Since you're using Java, I wouldn't rely solely on a regex here:

String input = "+123,456.789";
int count = input.replaceAll("[^0-9+]", "").length();
if (input.matches("^\\+?[0-9.,()\\-\\s]+$") && count >= 9 && count <= 15) {
    System.out.println("PASS");
}
else {
    System.out.println("FAIL");
}

This approach allows us to just use straightaway your original regex. We handle the length requirements of numbers (and maybe plus) using Java string calls.

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