Reputation: 11232
I want to match 1234 5678
or 12345678
Is this regular expression wrong?
if(!number.matches("^\\d{4}[, ]\\d{4}$")){
throw new Exception(" number is not valid : "+number);
}
Upvotes: 1
Views: 376
Reputation: 1999
Perhaps this is a good time to bring up the online Regex interactive tutorial. Great tool for playing around with Regex expressions without having to mess up your own code.
Upvotes: 0
Reputation: 179046
Do you want to match the comma as well? [, ]
matches a comma or a space char. The effect you're going for looks like ( |)
, except there are better ways to do it:
I think what you're looking for is:
/^\d{4}\s?\d{4}$/
Note that the \s can match any space char, including newlines. If you only want to match the space char ' '
, then use the following:
/^\d{4}[ ]?\d{4}$/
Upvotes: 1
Reputation: 5874
there is modifcation required to match '12345678'
use this regular expression : "^\d{4}[, ]?\d{4}$"
Hope this helps
Upvotes: 0
Reputation: 141598
You are close, you need to specify that the space/comma is optional with a quantifier. ?
is a good one because it means "zero or one". So your expression would be
^\d{4}[, ]?\d{4}$
Upvotes: 1