john
john

Reputation: 11669

validate string made up of numbers only separated by whitespace

I have a String which can only have integers separated by whitespace. For example:

1 2 3
4 5 6
9 8 7
1 p 3 // it should not pass

So my string should always have numbers in it separated by whitespace so that's why I added this regex check to validate the string but it's not working:

String line = "1 2 3"; // "1 p 3"
if(!line.matches("[ ]?\\d+")) {
    //it should come here for "1 p 3" string
}

What's wrong with my regex here?

Upvotes: 1

Views: 108

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

.matches will only evaluate to true if the whole string matches the regular expression. (you could think of it as being implicitly surrounded by ^ and $.) So, to validate a string with only numbers with whitespace between, use:

\d+(?: \d+)*

https://regex101.com/r/wK9WhP/1

Note that there's no need for a character set with only a single character in it - easier to leave out the character set entirely.

String line = "1 2 3"; // "1 p 3"
if(line.matches("\\d+(?: \\d+)*")) {
    System.out.println("match");
} else {
    System.out.println("no match");
}

Upvotes: 2

Related Questions