正则表达式排除 101 和 110

发布于 2024-08-10 16:17:44 字数 287 浏览 3 评论 0原文

接受语言 {0,1} 上的所有内容但不包含子字符串 110 或 101 的正则表达式是什么?

接受:

  • 111111
  • 000011111
  • 100001000001001
  • 010
  • 1

拒绝:

  • 100110
  • 010100
  • 123

编辑:根据下面答案的评论,这个问题要求一个正式的正则表达式。

What is a regexp that accepts everything over the language {0,1} but has no substring 110 or 101?

Accept:

  • 111111
  • 000011111
  • 100001000001001
  • 010
  • 1

Reject:

  • 100110
  • 010100
  • 123

Edit: Per comments on answers below, this question is asking for a formal regular expression.

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

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

发布评论

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

评论(6

掩于岁月 2024-08-17 16:17:44

这就是解决方案(即使没有前瞻):

/^0*(11*$|10$|100+)*$/
  • 从任意数量的零开始。
  • 循环(知道:到目前为止解析的字符串不是以“1”或“10”结尾)
    • “1$”可以(&停止)
    • 如果找到“11”,那么在到达末尾之前您将无法读取除 11 之外的任何内容
    • “10 美元”就可以了。
    • 如果您读到“10”并想继续,请读一个或多个零。然后返回循环。

This is the solution (even without lookahead):

/^0*(11*$|10$|100+)*$/
  • Start off with any number of zeros.
  • Loop (know: the string parsed so far does not end with "1" or "10")
    • "1$" is ok (&stop)
    • If you find "11", then you can't read any thing except ones until you reach the end
    • "10$" is ok.
    • If you read "10" and want to go on, read one or more zeros. Then go back to the loop.
滿滿的愛 2024-08-17 16:17:44

您最好检查它是否匹配/101|110/

You'd be best off checking if it doesn't match /101|110/

秋意浓 2024-08-17 16:17:44

假设您的正则表达式引擎支持前瞻,这似乎可行。

/^(1(?!01|10)|0)*$/

This seems to work, assuming that your regex engine supports lookahead.

/^(1(?!01|10)|0)*$/
最初的梦 2024-08-17 16:17:44

仅限于正式的正则表达式表示法:

((1|0*|0*1)(000*))*0*(10*|1*)

Limited to formal regular expression notation:

((1|0*|0*1)(000*))*0*(10*|1*)
回心转意 2024-08-17 16:17:44

这应该有效:

/^([01])\1*$/

This should work:

/^([01])\1*$/
蓝海 2024-08-17 16:17:44

相应的DFA很容易画出来。

当受到公认的“正式”正则表达式语法的限制时,没有相应的有限大小的正则表达式(缺乏完整代数中必需的“and”、“xor”、“not”等琐碎运算符)

但是有很多解决方案,像这样的

(0|100|(1|10|11*)$)*

也可以通过所有格匹配来解决。 (111+$) 是 111++

The corresponding DFA is easy to draw.

There is no corresponding regex of finite size when being limited by the accepted "formal" regex syntax (lack of trivial operators like "and", "xor", "not" which are necessary in a complete algebra)

But there are many solutions , like this one

(0|100|(1|10|11*)$)*

It can be solved with possessive matching too. (111+$) is 111++

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