swiftcode
swiftcode

Reputation: 3059

Regex to match certain digit pattern

I want to build a regex expression that allows me to parse through text files with thousands of lines, and each line contains one number with a variable size of digits.

Each number only can contain either the digits 1 or 0 (zero).

The requirement is there MUST be at least 3 1's in the number, and at least one zero. Therefore, the minimum required size of each number is 4 and it has unlimited maximum.

For example, it has to match:

000000111 - has at least 1 zero and 3 ones
1110 - same thing
11111000 - same thing
111 - FAIL, because it's under 4 digits long
0000000011 - FAIL, needs at least 3 ones

Can anyone help me please? My problem is that I can't determine how to find 'at least 3 ones and one zero anywhere in the number', key word being anywhere.

Upvotes: 0

Views: 297

Answers (2)

user712850
user712850

Reputation:

Unless this is strictly a regex exercise/practice, this would be more easily done by hand. (and since the regex would be complicated (im guessing), it would be way more efficient)

int ones = 0;
int zeroes = 0;
for(int i=0;i<str.length();++i)
{
    if(str[i] = '0')
        ++zeroes;
    else if(str[i] = '1')
        ++ones;
}

if(ones+zeroes >= 4 && ones >=3 && zeroes >= 1)
    return true;

Upvotes: 0

Qtax
Qtax

Reputation: 33908

You could match such numbers with:

(?=1*0)(?:0*1){3}[10]*

(?=1*0) make sure there is at least 1 0 with a lookahead (?=...)

(?:0*1){3} match the number with 3 1s

[10]* match the rest or the number

Upvotes: 4

Related Questions