Reputation: 2499
my source
Matcher matcher = Pattern.compile("[0-9]").matcher("35423523");
matcher.matches()
- now is false
but I need to matcher.matches() - true
- because the string is all numbers
or for example
Pattern.compile("[0-9A-Za-z]").matcher("35dwedwfeASADdfd423523");
- must be true
or Pattern.compile("[0-9]").matcher("354ccwq23523");
- must be false
or Pattern.compile("[0-9a-z]").matcher("354ccwq23523");
- must be true
how to do that ?
Upvotes: 1
Views: 186
Reputation: 8029
Pattern.compile("[0-9]+").matcher("35423523");
TRUE
Pattern.compile("[0-9A-Za-z]+").matcher("35dwedwfeASADdfd423523");
TRUE
Pattern.compile("[0-9]+").matcher("354ccwq23523");
FALSE
Pattern.compile("[0-9a-z]+").matcher("354ccwq23523");
TRUE
If you want to match certain lengths you could use [0-9]{1, 4}
(lower limit -> upper limit)
Upvotes: 2
Reputation: 143906
The matches()
method checks the entire region against the pattern. That means your pattern needs to match the entire String:
Matcher matcher = Pattern.compile("[0-9]+").matcher("35423523");
and
Pattern.compile("[0-9A-Za-z]+").matcher("35dwedwfeASADdfd423523");
From the javadocs:
Returns true: if, and only if, the entire region sequence matches this matcher's pattern
Upvotes: 2
Reputation: 1949
Your regex says that the string can only be one character wide, if you want more you should use repetition. Then it would look like this: [0-9]+
or [0-9A-Za-z]+
.
Upvotes: 5