-2

I've tried to write a grammar for the language. Here is my grammar:

S -> aS | bS | λ

I also wanted to generate the word "bbababb" which does not have two consecutive a's. I started with, bS => bbS => bbaS => bbabS => bbabaS => bbababS => bbababbS => bbababbλ => bbababb.

And finally I tried the following regular expression, (a+b*)a*(a+b*)

I really appreciate your help.

OHO33
  • 7
  • Both that grammar and regular expression accept the string "aa". You want something more like `(abb*|bb*)*`. – Welbog Apr 09 '21 at 19:30

2 Answers2

1

Let's try to write some rules that describe all strings that don't have two consecutive a's:

  1. the empty string is in the language
  2. if x is a string in the language ending in a, you can add b to the end to get another string in the language
  3. if x is a string in the language ending in b, you can add an a or a b to it to get another string in the language

This lets us write down a grammar:

S -> e | aB | bS
B -> e | bS

That grammar should work for us. Consider your string bbababb:

S -> bS -> bbS -> bbaB -> bbabS 
  -> bbabaB -> bbababS -> bbababbS
  -> bbababb

To turn a regular grammar such as this into a regular expression, we can write equations and solve for S:

S = e + aB + bS
B = e + bS

Replace for B:

S = e + a(e + bS) + bS
  = e + a + abS + bS
  = e + a + (ab + b)S

Now we can eliminate recursion to solve for S:

S = (ab + b)*(e + a)

This gives us a regular expression: (ab + b)*(e + a)

Patrick87
  • 27,682
  • 3
  • 38
  • 73
  • `(ab + b)*(e + a)` as a regular expression does not do what you think it does. For example, it would match this string `"ab bab bab bab be a"` – Bohemian Apr 09 '21 at 21:33
-1

a must always be followed by b, except the last char, so you can express it as "b or ab, with an optional trailing a":

\b(b|ab)+a?\b

See live demo.

\b (word boundaries) might be able to be removed depending on your usage and regex engine.

Bohemian
  • 412,405
  • 93
  • 575
  • 722