Failing with regular expression
I am writing the code in Java.
I am trying to write regular exception which valid this rule:
- the input must be only dig开发者_StackOverflow社区its.
- the input must
- start only with 03 or 02 or 08 or 09 or 04
- and afterwards must have only 1 or 2 or 3 or 7 digits.
example:
success inputs:
031, 0822, 097777777
fail inputs:
06, 0622, 09666666, 084444.
I tried to do this, but cant get it right.
^0([23894]\d{1}|\d{2}|\d{3}|\d{7})
thanks all,
ray.
You've messed up the the grouping. Try
^0[23894](?:\d|\d{2}|\d{3}|\d{7})$
To understand why:
^a(bc|d)$
matches abc
or ac
and not abd
.
Things don't go as you expect them to go because your regex:
^0([23894]\d{1}|\d{2}|\d{3}|\d{7})
actually means:
^0
(
[23894]\d{1} // b1
| // OR
\d{2} // b2
| // OR
\d{3} // b3
| // OR
\d{7} // b4
)
So it matches a 0
at the start followed by either b1
, b2
, b3
or b4
.
Try this instead:
^0[23894](\d{1,3}|\d{7})$
Try changing it to ^0[23894](\d{1,3}|\d{7})$
(untested). What you wrote looks for 0, followed by either 2,3,8,9,4 and one other digit, or two digits, or three digits, or seven digits. The {1,3}
specifies a repetition range of 1-3 occurances.
The $
anchors the expression at the end of the string; if you omit it, any string that starts with the pattern will be valid.
There are two problems with this:
You had your parentheses in the wrong place, you should only alternate on the length of the digits at the end
You need the "match end of string" symbol at the end to make sure it matches the inital digits and then either 1/2/3/7 other digits
try this:
^0[23894](\d{1}|\d{2}|\d{3}|\d{7})$
try this one:
^0([23894](1|2|3|7)*)
精彩评论