Bob
Bob

Reputation: 59

regular expression to tease out the strings that contain at least two 0s and at most one 1?

I have tried (^.*(?0){2}.*$) to catch the 0's but don't know how to catch the 1's

So for the following data:

00
110
100
11110011
00111101
00101010
11000000
00000001
10000000

The ones that would return would be 100, 00000001, and 10000000

Upvotes: 0

Views: 301

Answers (5)

glenn jackman
glenn jackman

Reputation: 246799

Using a negative lookahead to filter out lines with two 1's or zero or one 0:

^(?!.*1.*1|[^0]*(0[^0]*)?$)

Upvotes: 0

enrico.bacis
enrico.bacis

Reputation: 31484

If your characters are just 0s and 1s like in your example you can do:

^(0+10+|100+|0+01)$

Here's a demo.

Upvotes: 2

alpha bravo
alpha bravo

Reputation: 7948

use this pattern

^(?=(?:.*0){2})(?=[^1]*1[^1]*$)([01]*)$  
  • ^ anchor at beginning
  • (?=(?:.*0){2}) lookahead for at least two 0's
  • (?=[^1]*1[^1]*$) lookahead for only one '1' to the end
  • ([01]*) capture any amount of 0's and 1's or change to (\d*) if required
  • $ anchor at end
    Demo

Upvotes: 0

kev
kev

Reputation: 161664

Try this regex:

^(?=.*0.*0.*)(?=.*1.*)(?!.*1.*1.*).*$

which is the same as:

^(?=.*0.*0.*)(?=[^1]*1[^1]*$).*$

Use look-ahead assertion:

  • at least 2 zero
  • at least 1 one
  • at most 1 one

DEMO

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

It works for any combination of numbers.

^(?=[02-9]*1[02-9]*$)\d*0\d*0\d*$

DEMO

Upvotes: -1

Related Questions