Regular expression for strings containing a's in multiples of 3

1.6k Views Asked by At

Can someone please tell me how to generate a regular expression for strings in which number of a's is a multiple of 3? The alphabet set is {a,b}.

I tried to construct a DFA for it first and then derive a RE from that. What I got was ((ba*)(ba*)(ba*))*.

1

There are 1 best solutions below

0
Tim Biegeleisen On

I would write the pattern as:

^b*(?:(?:ab*){3})*$

This matches:

  • ^ from the start of the string
  • b* optional leading b zero or more times
  • (?:
    • (?:ab*){3} match a followed by zero or more b 3 times
  • )* match this group zero or more times
  • $ end of the string

Demo