'Regular Expressions: Strings of an even length in which all the 'o’s (if any) come before all the 'g’s (if any)
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?
Solution 1:[1]
A string that where all os precede all gs and is of even lengths can have a few different shapes:
- The empty string
- A positive, even number of
os, nogs:/(oo)+/ - No
os, a positive even number ofgs:/(gg)+/ - An even number of
os followed by an even number ofgs:/(oo)+(gg)+/ - An odd number of
os followed by an odd number ofgs:/o(oo)*g(gg)*/
Putting it all together you get /(oo)*(gg)*|o(oo)*g(gg)*/
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | isaactfa |
| Solution 2 | The fourth bird |
