0

I'm working on a regex that needs this format:

X = Integer

XXXX-XX

Where it only matches if follow these rules:

  1. Before "-" it need to be 4 integers.
  2. The "-" is optional, but if there is a 5th character it has to be "-"
  3. After "-" it can be 0, 1 or 2 integers
  4. The "-" only matches if there is integers after it.

Here is what i have been done for each rule respectively to work:

The regex: (\d{4})-?(\d{1,2})?((?<!(\d{5})|(\d{4}-)))

  1. (\d{4})
  2. -? and ((?<!(\d{5})|(\d{4}-))) (negative lookahead to avoid match "11111")
  3. (\d{1,2})?
  4. ((?<!(\d{5})|(\d{4}-)))

My problem is, i want to discard the whole string if anything is wrong.

For example

In: 123456 It matches 123456

In: 1234-5678 It matches 1234-5678

I would like to discard the whole string if it doesnt match the pattern, how can i do it?

João Hamerski
  • 315
  • 3
  • 16
  • 2
    Add anchors to the regex: `^` to match the start of the string, and `$` to match the end. – Pointy Sep 10 '21 at 14:18

0 Answers0