简体   繁体   English

包含a和偶数b的字符串的正则表达式

[英]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*

正则表达式可视化

Debuggex Demo Debuggex演示

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*$

Here is the best solution because i follow the algorithm for conversion from DFA to regular expression (done by pen): 这是最好的解决方案,因为我遵循从DFA转换为正则表达式的算法(由笔完成):

(a*|ba*b)*

You can test it here and you can learn about this algorithm watching this video . 您可以在此处进行测试,并观看此视频,以了解有关此算法的信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 查找包含偶数个a和偶数个b的所有a和b字符串的正则表达式? - Regular expression to find all strings of a's and b's that contain an even number of a's and an even number of b's? 带有偶数个 b 后跟字母 c 后跟奇数个 a 的字符串的正则表达式 - Regular Expression for Strings with even number of b's followed by the letter c followed by an odd number of a's 偶数个1的位串的正则表达式 - Regular expression for bit strings with even number of 1s 具有偶数个零和一的字符串的正则表达式 - Regular expression for strings with an even number of zeroes and ones “ {a,b}上的字符串的偶数奇数语言”的正则表达式 - Regular expression for "even odd language of strings over {a, b} 正则表达式将字符串与z的相同数量匹配,而b与y相同 - Regular expression that matches Strings with the same amount of a's as z's and b's as y's 正则表达式匹配偶数为1的字符串,并以0开头和结尾 - Regular Expression to match a string with an even number of 1's and starts and ends with a 0 如何为包含“a”,“b”和“c”但不超过2“b”和3“c”的所有字符串编写简洁的正则表达式 - How to write a concise regular expression for all strings containing “a”s, “b”s, and “c”s but no more than 2 “b”s and 3 “c”s 正则表达式将电话号码与[a | b]模式匹配 - Regular expression match phone number with [a|b] pattern 在perl中编写一个正则表达式,用于a的序列,后跟相等数量的b - to write a regular expression in perl for sequence of a's followed by an equal number of b's
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM