Home > Net >  Regular Expressions: Strings of an even length in which all the 'o’s (if any) come before all t
Regular Expressions: Strings of an even length in which all the 'o’s (if any) come before all t

Time:05-08

I'm pretty new to regular expressions so I could use some help. Right now I have:

(oo|og) (oo|gg|og|go)*

for the alphabet = {o,g} which I made from a previous task, as an answer to "Strings of an even length, whose first character is 'o'".

Now I have to make a regular expression for strings of an even length in which all the 'o’s (if any) come before all the 'g’s (if any).

How would I do that? Is it possible to modify my previous answer to accommodate the change?

CodePudding user response:

A string that where all os precede all gs and is of even lengths can have a few different shapes:

  1. The empty string
  2. A positive, even number of os, no gs: /(oo) /
  3. No os, a positive even number of gs: /(gg) /
  4. An even number of os followed by an even number of gs: /(oo) (gg) /
  5. An odd number of os followed by an odd number of gs: /o(oo)*g(gg)*/

Putting it all together you get /(oo)*(gg)*|o(oo)*g(gg)*/

CodePudding user response:

If you don't want to match emtpy strings, and using a lookahead is supported, you can assert pairs of o and g to the end of the string to make sure that it is even.

Then match optional o's followed by optional g's.

^(?=(?:[og]{2}) $)o*g*$

See a regex101 demo.

Without lookarounds, you could repeat optional pairs of oo, optinally match a single pair or og and optionally repeat matching pairs of gg

^(oo)*(?:og)?(gg)*$

See a regex101 demo.

  • Related