Lets say I have a string and it could be
1234
or
12 34
or
1 2 3 4 5
It doesn't matter about the number of digits or whitespace, just so that it accepts a string that has only digits and if there is whitespace within string of digits it will still accept it. How would I write the regex pattern for this?
Use String#matches()
and a regex:
if (str.matches("[\\d\\s]+"))
// string is acceptable
If it's acceptable to have only whitespace, then the regexp you want is "[\\d\\s]+"
If there has to be one or more digits, then you could use "\\s*(\\d\\s*)+"
Note that I've doubled up the backslashes, assuming you're writing this in Java source, rather than reading it in from some other source of text. The actual regexp in the second case is \s*(\d\s*)+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With