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 hyphen. 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:
(...)
and (?:...)
- Allows grouping of quantifiers, like ?
. [...]
- 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.