简体   繁体   中英

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 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:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM