[英]Regular expression for strings that cointains a and an even number of b's
How to define a regular expression to feature the following language? 如何定义正则表达式以使用以下语言?
L = {w ∈ {a, b}* | L = {w∈{a,b} * | w has an even number of b's} w的b为偶数}
I tried to create the related automaton: 我试图创建相关的自动机:
and from that i tried to apply the algorithm to obtain regular espression from DFA and i get this formula: a*ba*b
. 然后我尝试应用该算法从DFA获取常规表达式,并得到以下公式: a*ba*b
。
Could this be the right answer? 这是正确的答案吗?
You are close but you need a a*
in the end of your pattern.You also need the anchors ^
and $
for specifying the start and end of your string.Then you can put all of your regex within a capture group and use *
to match any even number if b
, and an a*
for zero number of b
: 您很接近,但是在模式的末尾需要一个a*
,还需要使用锚点^
和$
来指定字符串的开始和结束,然后可以将所有正则表达式放入捕获组中并使用*
来匹配任何偶数如果b
,和a*
零数的b
:
^((a*ba*ba*)*|a*)$
Note : |
注 : |
is a logical OR and makes your regex engine match (a*ba*ba*)*
or a*
. 是逻辑或,并使您的正则表达式引擎匹配(a*ba*ba*)*
或a*
。
You can also make it more elegant but as you are not familiar very much with regex first i suggested the preceding pattern. 您也可以使其更优雅,但由于您对regex并不十分熟悉,所以我建议使用上述模式。
For example the following will works : 例如,以下将起作用:
^(((a*b){2})*)a*$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.