0
public static boolean validateState (String state)
{
return state.matches( "[1-9]\\d{2}-[1-9]\\d{4}" ) ;
}

Why this function takes 3 digit before hyphen and 5 after hyphen when i have put 2 and 4 in the brackets? Kindly Help..

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Usman
  • 306
  • 1
  • 3
  • Easy, because you put `[1-9]` before it, you probably want `\\d{2}-\\d{4}`, but note that `\d` is `[0-9]` and not `[1-9]` – Davio Jul 15 '14 at 13:51

2 Answers2

3

Remove the [1-9] in both cases. You're actually trying to match:

  • a digit (1-9), followed by
  • two digits, followed by
  • a hyphen, followed by
  • a digit (1-9), followed by
  • four digits

Or to put it more succinctly: [0-9] is equivalent to \\d.

You probably either need [1-9]\\d-[1-9]\\d{3} or just \\d{2}-\\d{4}.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

For the RegEx which you have provided "[1-9]\d{2}-[1-9]\d{4}"


a) [1-9] accepts one digit
b) d{2} accepts two digits

So, totally it accepts 3 digits(before the hyphen, i.e, for "[1-9]\d{2}" part).

Likewise, after hyphen also it will accept 4 digits.

You probably want to use any one of the following:
1) \d{2}-\d{4}
2) [1-9]\d{1}-[1-9]\d{3}

abhijitcaps
  • 594
  • 8
  • 7