How do I fix my regex ^\d+[-\d]?\d* to match 123-45 but not 123-?
I need a regular expression to match an ID in the following format
123
or
123-45
There can by any amount of numbers before an after the h开发者_C百科yphen. The problem right now is that my expression matches 123-
and I need it not too (hyphen is optional, but if it's present then there MUST be at least one digit after it).
I have tried
^\d+[-\d+]?
and ^\d+[-\d]?\d*
, but neither work.
Try something like:
^\d+(?:-\d+)?$
You want to have -
optional with at least a single digit. [-\d]
allows a hyphen or a digit, followed by zero digits. A similar pattern in ^\d+(?:-\d)?\d*$
.
See also:
- Capturing and non-capturing groups -
(...)
and(?:...)
- Allows grouping of quantifiers, like?
. - Character classes -
[...]
- Allows selecting a single character out of a set.
This should do it:
\d+(?:-\d+)?
As Kobi said - you almost had it right, you just mixed up the square with the round brackets
How about: \d+-?
Matching all digits and optionally a hyphen
Try:
^\d+[-\d]?\d+
Replacing the *
with a +
forces it to match one or more of the preceding element, rather than zero or more.
精彩评论