简体   繁体   English

使用正则表达式确定字符串是偶数还是奇数长度

[英]Determine if string is even or odd length with regular expression

I am having trouble building a regular expression with the set of strings over {a, b, c} that is an odd length with exactly one a . 我在使用{a, b, c}上的字符串集构建正则表达式时遇到问题,这个字符串是一个odd长度, 只有一个a Here is my best attempt so far: 到目前为止,这是我最好的尝试:

(bb|bc|cb|cc)*a(bb|bc|cb|cc)*

This does good for even b and c on either side of the a , but does not account for a odd b and c combination on either side of the a . 这不利于甚至bc在两侧的a ,但不占奇bc在两侧组合a

Any hints? 任何提示?

Your string will be a prefix followed by a followed by a suffix . 你的字符串将是一个前缀,后跟一个接着一个后缀

Both prefix and suffix can be zero length. 前缀后缀都可以是零长度。 If not, they have to be either both even or both uneven. 如果不是,它们必须是均匀的或两者都不均匀。 This means you have two main cases. 这意味着您有两个主要案例。

EVENPREFIX a EVENSUFFIX | UNEVENPREFIX a UNEVENSUFFIX

Try this ( incomplete and wrong ): 试试这个( 不完整错误 ):

([bc][bc])*a([bc][bc])*|([bc][bc][bc])*a([bc][bc][bc])*

There is still one uneven case missing: a single [bc] : 还有一个不平衡的案例缺失:一个[bc]

(([bc][bc])*a([bc][bc])*)|([bc]([bc][bc])*a[bc]([bc][bc])*)

According to http://www.fileformat.info/tool/regex.htm , this matches 根据http://www.fileformat.info/tool/regex.htm ,这匹配

  • a
  • cac
  • ccabb

I expect it matches the rest too... 我希望它与其他的相匹配......

The left side guarantees even (or empty) sequences of b or c . 左侧保证bc偶数(或空)序列。 The right side is either a single b or c followed by a multiple of two (so that it stays uneven). 右侧是单个bc后跟两个的倍数(因此它保持不均匀)。

Kobi came up with this refinement of the above: Kobi想出了上述的改进:

([bc][bc])*(a|[bc]a[bc])([bc][bc])*

How does this work? 这是如何运作的?

The first group is guaranteed to be even. 第一组保证是平等的。 The second group is guaranteed to be uneven with a single a inside. 第二组是保证是不均匀的具有单个a内部。 The third group is guaranteed to be be even. 第三组保证是平等的。 Thus, the whole is guaranteed to be uneven. 因此,整体保证不均匀。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM