Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a string in Java equals to a regex pattern?

Tags:

java

regex

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?

like image 513
user3001301 Avatar asked Jan 28 '14 01:01

user3001301


2 Answers

Use String#matches() and a regex:

if (str.matches("[\\d\\s]+"))
    // string is acceptable
like image 160
Bohemian Avatar answered Oct 18 '22 18:10

Bohemian


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*)+

like image 29
Dawood ibn Kareem Avatar answered Oct 18 '22 19:10

Dawood ibn Kareem