Asha
Asha

Reputation: 11232

How do I use a regular expression to match an eight-digit number that can also have a space in the middle?

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

Answers (6)

Bnjmn
Bnjmn

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

A_Var
A_Var

Reputation: 1036

 ^\d{4}[\s]?\d{4}$ 

Try this without the comma.

Upvotes: 0

zzzzBov
zzzzBov

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

wizzardz
wizzardz

Reputation: 5874

there is modifcation required to match '12345678'

use this regular expression : "^\d{4}[, ]?\d{4}$"

Hope this helps

Upvotes: 0

vcsjones
vcsjones

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

sbeam
sbeam

Reputation: 4892

try a quantifier after the []

^\d{4}[\s,]?\d{4}$

Upvotes: 6

Related Questions