正则表达式:所有均匀长度的字符串,其中所有o(如果有)在所有' g' g’ s之前

发布于 2025-01-26 21:03:38 字数 251 浏览 2 评论 0 原文

我对正则表达式非常陌生,因此我可以使用一些帮助。 现在我有:

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

for Alphabet = {o,g} 我从以前的任务中做出了这一点,以此作为“均匀长度的字符串,其第一个角色为'o'”的答案。

现在,我必须对均匀长度的字符串进行正则表达式,其中所有'o(如果有)都在所有'g(如果有)之前。

我该怎么做?是否可以修改我以前的答案以适应更改?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我们的影子 2025-02-02 21:03:38

所有 o s之前所有 g s且均匀长的字符串可以具有几种不同的形状:

  1. 空字符串
  2. 是正面的,一个正面,甚至是 o的数字 s,否 g s:/(oo)+/
  3. no o s,均匀数量 g s:/(gg)+/
  4. 均匀的 o s,然后是均匀数 g s:<代码>/(oo)+(gg)+/
  5. o s的奇数,然后是 g s的奇数数:/o( oo)*g(gg)*/

将其全部放在一起,您得到/(oo)*(gg)*| O(oo)*g(gg)*/

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)*/

ら栖息 2025-02-02 21:03:38

如果您不想匹配emtpy strings,并且支持使用lookahead,则可以将O和G的对成对固定到字符串的末端,以确保其均匀。

然后匹配可选的O,然后是可选的G。

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

请参阅a regex101 demo

如果没有lookarounds,则可以重复 oo 的可选对,选择匹配单对或 og ,并且可选地重复匹配 gg > gg

^(oo)*(?:og)?(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.

^(?=(?:[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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文