1

I have to write a regex that detects either 6 digits or 9 digits - meaning:

ID 123 - it should not meet the regext as it is 3 digits
ID 1234 - it should not meet the regext as it is 4 digits
ID 12345 - it should not meet the regext as it is 5 digits
ID 123456 - it should meet the regex it is 6 digits <==========
ID 1234567 - it should not meet the regext as it is 7 digits
ID 12345678 - it should not meet the regext as it is 8 digits
ID 123456789 - it should meet the regext as it is 9 digits <==========
ID 1234567890 - it should not meet the regext as it is 10 digits
ID 12345678901 - it should not meet the regext as it is 11 digits

and so on... you got the idea?

Can anyone help me with the regex for this one?

3 Answers3

3

You may try to use this pattern:

\b(\d{6}|\d{9})\b
cn007b
  • 16,596
  • 7
  • 59
  • 74
2

Or another one:

\b\d{6}(?:\d{3})?\b

See demo at regex101

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
1

If the ID part should be matched, you could use an alternation to match either 6 or 9 digits.

Use anchors to assert the start ^ and the end $ of the string or add word boundaries \b to the beginning and the end of the pattern.

The digits are in the first capturing group.

^ID (\d{6}|\d{9})$
The fourth bird
  • 154,723
  • 16
  • 55
  • 70