正则表达式中的模运算符 [英] Modulo operator in a regular expression
本文介绍了正则表达式中的模运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个正则表达式来接受任何二进制字符串,唯一的标准是 0 的数量不是 3 的因数([0 的数量] % 3 != 0).如何实现?
I am attempting to write a regular expression to accept any binary strings with the only criteria being that the number of 0s is not a factor of 3 ([number of 0s] % 3 != 0). How can this be achieved?
推荐答案
如果您的正则表达式风格支持 递归模式,你可以使用这个:
If your regex flavour supports recursive pattern, you could use this:
^(1*01*)(?1)?(?:(?1)(?1)(?1))*1*$
如果不是,则将所有 (?1)
替换为 (1*01*)
If it doesn't, replace all (?1)
by (1*01*)
说明:
^ : begining of string
( : start group 1
1*01* : that contains 0 or more 1, one 0 and 0 or more 1
) : end group
At this time, we have one 0
(?1)? : Same pattern as group 1 (ie. 1*01*), optional
we have now one or two 0
(?: : non capture group
(?1)(?1)(?1): pattern 1 repeated 3 times
)* : 0 or more times
we have one or two 0 followed by three 0,
so the number of zeros modulo 3 != 0
1* : 0 or more 1
$ : end of string.
这篇关于正则表达式中的模运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文