0

If I have a string and I need to write a regex pattern to find match only for a and aa, but not more than 2 consecutive a. For instance, baaab is not a match because 3 a appear together, but abaa is a match. Can I write a regex pattern for this purpose?

Here are something that I tried:

  • pattern = 'a{1,2}', but this pattern also matches 'baaab'.
  • pattern = 'a{1,2}[^a]', but it failed to match 'abaa'
  • pattern = 'a{1,2}[^a]?', but it also matches 'baaab'

So what's the correct pattern I should use?

larueroad
  • 167
  • 8
  • Does this answer your question? [How to negate the whole regex?](https://stackoverflow.com/questions/2637675/how-to-negate-the-whole-regex) – tripleee Aug 12 '20 at 06:50
  • See also https://stackoverflow.com/questions/7520704/sed-can-my-pattern-contain-an-is-not-character-how-do-i-say-is-not-x – tripleee Aug 12 '20 at 06:51

1 Answers1

1

You could use a negative lookahead assertion which enforces that three or more a's do not appear:

^(?!.*aaa).*a{1,2}.*$

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360