在正则表达式中顺序无所谓吗? [英] Does order not matter in regular expressions?

查看:118
本文介绍了在正则表达式中顺序无所谓吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看此stackoverflow链接中提出的问题(要求a的奇数)来查找具有 a 奇数且Σ= { a,b}

I was looking at the question posed in this stackoverflow link (Regular expression for odd number of a's) for which it is asked to find the regular expression for strings that have odd number of a over Σ = {a,b}.

最有价值的评论给出的答案是 b *(ab * ab *)* ab *

The answer given by the top comment which works is b*(ab*ab*)*ab*.

我很困惑- a 就放在最后一个 b *之前,此顺序实际上有关系吗?为什么不能是 b * a(ab * ab *)* b * (放置 a 的地方)在第一个 b * 之后还是其他排列方式?

I am quite confused - a was placed just before the last b*, does this ordering actually matter? Why can't it be b*a(ab*ab*)*b* instead (where a is placed after the first b*), or any other permutation of it?

我感到困惑的另一件事是为什么它是(ab * ab *)* ,而不是(b * ab * ab *)* b * ab * ab * 不是精确地具有2个 a 的准确定义吗?

Another thing I am confused about is why it is (ab*ab*)* and not (b*ab*ab*)*. Isn't b*ab*ab* the more accurate definition of 'having exactly 2 a'?

推荐答案


为什么不能是 b * a(ab * ab *) * b * 代替?

b * a(ab * ab *) * b * 不起作用,因为它将要求字符串在第一个非前导之前具有两个连续的 a s b ,不是吗?例如, abaa 不会与您建议的正则表达式匹配。在类似 Regex101 之类的网站上使用正则表达式调试器,亲自体验一下。

b*a(ab*ab*)*b* does not work because it would require the string to have two consecutive as before the first non-leading b, wouldn't it? For example, abaa would not be matched by your proposed regex when it should. Use the regex debugger on a site like Regex101 to see this for yourself.

另一方面,将整个 ab * 部分移到开头( b * ab *(ab * ab *)* )也可以。

On the other hand, moving the whole ab* part to the start (b*ab*(ab*ab*)*) works as well.


为什么是(ab * ab *)* 而不是(b * ab * ab *)*

(b * ab * ab *)* 可以工作,但第一个 b * 是非常多余的,因为剩下的 b 都将与末尾的 b * 匹配组。群组前还有 b * ,这导致 b * 无法匹配任何内容,因此这是多余的。

(b*ab*ab*)* does work, but the first b* is quite redundant because whatever b there is left, will be matched by the last b* in the group. There is also a b* before the group, which causes the b* to not be able to match anything, hence it is redundant.

这篇关于在正则表达式中顺序无所谓吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆