正则表达式:所有均匀长度的字符串,其中所有o(如果有)在所有' g' g’ s之前
我对正则表达式非常陌生,因此我可以使用一些帮助。 现在我有:
(oo | og)+(oo | gg | og | go)*
for Alphabet = {o,g} 我从以前的任务中做出了这一点,以此作为“均匀长度的字符串,其第一个角色为'o'”的答案。
现在,我必须对均匀长度的字符串进行正则表达式,其中所有'o(如果有)都在所有'g(如果有)之前。
我该怎么做?是否可以修改我以前的答案以适应更改?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所有
o
s之前所有g
s且均匀长的字符串可以具有几种不同的形状:o的数字
s,否g
s:/(oo)+/
o
s,均匀数量g
s:/(gg)+/
o
s,然后是均匀数g
s:<代码>/(oo)+(gg)+/o
s的奇数,然后是g
s的奇数数:/o( oo)*g(gg)*/
将其全部放在一起,您得到
/(oo)*(gg)*| O(oo)*g(gg)*/
A string that where all
o
s precede allg
s and is of even lengths can have a few different shapes:o
s, nog
s:/(oo)+/
o
s, a positive even number ofg
s:/(gg)+/
o
s followed by an even number ofg
s:/(oo)+(gg)+/
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)*/
如果您不想匹配emtpy strings,并且支持使用lookahead,则可以将O和G的对成对固定到字符串的末端,以确保其均匀。
然后匹配可选的O,然后是可选的G。
请参阅a regex101 demo 。
如果没有lookarounds,则可以重复
oo
的可选对,选择匹配单对或og
,并且可选地重复匹配gg
> gg请参阅a regex101 demo 。
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.
See a regex101 demo.
Without lookarounds, you could repeat optional pairs of
oo
, optinally match a single pair orog
and optionally repeat matching pairs ofgg
See a regex101 demo.