Eloijza Pavlova Eloijza Pavlova - 8 months ago 29
Java Question

How do implement this regex function in java?

The string should be 15 character maximum, composed of numbers only and there should be at least two one-character sized whitespace anywhere in the string.

It is easy to find the solution for numeric only, I'm getting stuck finding adding the condition for the whitespace.

I tried searching the most frequently asked regex question but couldn't find anything similar.


Additional conditions

  • whitespaces cannot be next to each other

  • they must not be placed in first or last character


You can use this regex: [0-9\s]{2,15}

And in your Java code you check if there are three parts separated by a whitespace:

String input =...;
if (input.matches("[0-9\\s]{2,15}") && (input.split(" ").length == 3) ) {
     System.out.println("valid input");     

Edited: Leading and ending whitespaces, connected whitespaces are not allowed