2 digits only allowed once (Regex) 2 digits only allowed once (Regex) unix unix

2 digits only allowed once (Regex)


This is the regex that will meet all of your conditions:

^b(?!(?:[^2]*2){2,})(?!(?:[^4]*4){2,})[b0-8]*b$
  • It starts and end with b Using ^b and $b
  • It comprises of only letter b and numbers 0-8 by[b0-8]*
  • It won't allow more than one digit 2 by using (?!(?:[^2]*2){2,})
  • It won't allow more than one digit 4 by using (?!(?:[^4]*4){2,})


Well, a regex for exactly 1 a would be [^a]*a[^a]* (that is, a possibly empty sequence of non-a's, followed by an a, followed by a possibly empty sequence of non-a's). I'll leave it an an exercise how to handle multiple lines & making sure this covers the whole level.

For exactly 1 a and 1 b: [^ab]*((a[^ab]*b)|(b[^ab]*a))[^ab]*, with the same caveats. Explanation: a sequence of non-a-or-b's, follow by EITHER 1) an a, a run of non-a-or-b's, and a b, or 2) a b, a run of non-a-or-b's, and an a, with THAT followed by a run of non-a-or-b's.


The answer is to use negative lookaheads anchored to start of input.

It's unclear what you're trying to match, so I will just use a placeholder <your-regex> for your current regex:

^(?!.*?2.*?2)(?!.*?4.*?4)<your-regex>

See a live demo of rhis correctly rejecting more than 1 "2".