How to fix my regex ^ \ d + [- \ d]? \ D * to match 123-45 but not 123-?

I need a regular expression to match an identifier in the following format

123 or 123-45

There can be any number of digits before the hyphen. The problem right now is that my expression matches 123-, and I don’t need it too much (a hyphen is optional, but if it is present, then there MUST be at least one digit after it).

I tried ^\d+[-\d+]? and ^\d+[-\d]?\d*but do not work.

+3
source share
5 answers

Try something like:

^\d+(?:-\d+)?$

You want to have -at least one digit optional. [-\d]allows a hyphen or digit, and then zero digits. Similar pattern to ^\d+(?:-\d)?\d*$.

. :

  • - (...) (?:...) - , ?.
  • - [...] - .
+9

:

\d+(?:-\d+)?
+2

Like Kobe said, you're pretty much everything right, you just mixed a square with parentheses

+1
source

How about: \ d + -?

Match all digits and optional hyphen

0
source

Try:

 ^\d+[-\d]?\d+

Replacing *with +makes it match one or more of the previous element, and not zero or more.

0
source

All Articles