0

I am trying to do the following and I tried to find examples of how to do a proper exclusion but I couldn't quite get the hang of it.

question

I am supposed to exclude the numbers 000, 666, and all numbers between 900-999.

This was my attempt at the question but it doesn't include the exclusion:

String p = "(^[0-9]{3})-([0-9]{2})-([0-9]{4}$)";

Which resulted in unnecessary matches: wrong answer

This is my attempt at trying the exclusion but I'm unsure how:

String p = "(^[^666000]{3})-([0-9]{2})-([0-9]{4}$)";

Which resulted in some matches:

enter image description here

Any help would be appreciated!

thecylax
  • 79
  • 6

1 Answers1

2

To match anything but 000, 666 and 900-999:

[1-578]\d\d|(?:0\d[1-9]|0[1-9]\d)|(?:6\d[0-57-9]|6[0-57-9]\d)

Regex101 Demo

How this works:

  • [1-578]\d\d first alternative matches all numbers starting with anything but 0, 6 and 9 i.e 1xx, 2xx, 7xx etc. as represented here [1-578] which essentially means 1-5 or 7 or 8.
  • (?:0\d[1-9]|0[1-9]\d) matches all numbers starting with 0 and ensures that the number shouldn't have all three zeroes
  • (?:6\d[0-57-9]|6[0-57-9]\d) matches all numbers starting with 6 and snsures that the number shouldn't have all three sixes

Testing:

Quick Test to validate if all are matched except 000, 666 and 900-999: Dotnet Fiddle

// Output for non-matching characters:
000, 666, 900, 901, 902, 903, 904, 905, 906, 907, 908, ... and so on
degant
  • 4,861
  • 1
  • 17
  • 29