anton broos
anton broos

Reputation: 427

Regex: number or 2 numbers separated by ' - '

Can someone help me with a regular expression? I'd paste mine here but Stackoverflow doesn't seem to allow it so here's a screenshot:

enter image description here

It must match any number or any 2 numbers separated by a '-' and also only the first match.

Upvotes: 0

Views: 387

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You can use

^\d+(?:\.\d+)?(?:\s*-\s*\d+(?:\.\d+)?)?$

See a regex demo.

Details:

  • ^ - start of string
  • \d+(?:\.\d+)? - one or more digits and an optional sequence of a . and one or more digits
  • (?:\s*-\s*\d+(?:\.\d+)?)? - an optional sequence of
    • \s*-\s* - a hyphen enclosed with zero or more whitespaces
    • \d+(?:\.\d+)? - one or more digits and an optional sequence of a . and one or more digits
  • $ - end of string.

Upvotes: 1

Related Questions