正则表达与计数

时间:2016-12-25 09:32:44

标签: regex

我有0和1的字符串。 我想要一个正则表达式,使得0的数量小于1的数量。

示例:

0111 - match (there is 1x0 and 3x1 and 1 < 3)
00011 - pattern fails (3x0 and 2x1 but 3<2 is false)
0101010 - pattern fails (4x0 and 3x1 but 4<3 is false)

4 个答案:

答案 0 :(得分:2)

使用pcre和可能的Perl,你可以使用递归模式:

^((?:0(?1)??1|1(?1)??0)*+)(?:1(?1))+$

demo

细节:

^
( # group 1: matches balanced 0 and 1 
    (?:
        0(?1)??1 # part that starts with 0 and ends with 1
                # (?1) calls the group 1 subpattern itself (recursion) 
      |
        1(?1)??0 # same thing for 1 ... 0
    )*+ # repeat
)
(?:
    1    
    (?1)
)+ # ensure there's at least one 1 that isn't matched by (?1)
$

使用.net regex引擎:

^(?>(?<c>0)|(?<-c>1))*(?(c)(?!$))(?:1(?>(?<c>0)|(?<-c>1))*(?(c)(?!$)))+$

demo

这次更直观:

(?<c>...)会增加一个计数器c,而(?<-c>...)会减少相同的计数器。当计数器c不为零时,条件(?(c)(?!$))失败(?!$)总是失败的子模式)

此模式的全局结构与前一个相同:

^ (balanced parts)* (?: 1 (balanced parts)* )+ $

pcre的另一种可能结构是:

^ (?: balanced parts | (1) )*+ (force to fail if capture group doesn't exist) $

pcre:

^(?:((?:0(?1)?1|1(?1)?0)+)|(1))*+(?(2)|(*F))$

答案 1 :(得分:1)

正则表达式用于匹配模式,但您似乎想要计算字符的实例。据我所知,这不是正则表达式。

您需要做的是创建一个数组或其他结构来保存您所追踪的特定字符的计数器值。然后,您将遍历输入字符串,并根据手头的字符更新相应的计数器。

答案 2 :(得分:1)

我认为你可以在没有正则表达式的情况下实现目标。

FOREACH:

subscribe

LINQ:

string s = "10101010011";
int zeros = 0;
int ones = 0;
foreach (char c in s)
{
    if (c == '0')
    {
        zeros++;
    }
    else
    {
        ones++;
    }
}
Console.WriteLine(zeros < ones);
Console.ReadLine();

答案 3 :(得分:1)

由于您没有指定语言。这是你在不使用正则表达式的情况下在Python中实现它的方法。您可以将此逻辑移植到您的语言中。

a= """0111
00011
0101010"""

a = a.split('\n')
print a

for b in a:
    zeroes = list(b).count('0')
    ones = list(b).count('1')
    if zeroes < ones:
        print b

输出:

['0111', '00011', '0101010']
0111