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 o
s precede all g
s and is of even lengths can have a few different shapes:
- The empty string
- A positive, even number of
o
s, nog
s:/(oo) /
- No
o
s, a positive even number ofg
s:/(gg) /
- An even number of
o
s followed by an even number ofg
s:/(oo) (gg) /
- An odd number of
o
s followed by an odd number ofg
s:/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.