-1

Given a series of bits, e.g 10100011110010101 and 010001001010100.

How can I write a regular expression to reflect the patterns where no 1s are neighbors?

For example, 010001001010100 is a good one, but 10100011110010101 is not as there are 1s neighboring.

edit:

Sorry my above statement may be misleading. i don't want to check whether a sequence is non-1-neighboring. I want to use an regex to find all non-1-neighborings.

Assume I have a very lone series of bits, I want to write a regex to find out all sub sequences where no 1s are neighbors.

Jackson Tale
  • 25,428
  • 34
  • 149
  • 271

5 Answers5

4

Simply "11" will return true if neighboring ones exist.

Regards

SamWhan
  • 8,296
  • 1
  • 18
  • 45
  • Sorry my above statement may be misleading. i don't want to check whether a sequence is non-1-neighboring. I want to use an regex to find all non-1-neighborings. – Jackson Tale Jan 13 '14 at 15:22
3

You can try with following regex:

^0*(10+)*1?$
hsz
  • 148,279
  • 62
  • 259
  • 315
  • @C.B. Ok, I've edited. I know that reverted regex will be simpler, but I give it as an example. :-) – hsz Jan 13 '14 at 15:16
  • To fix this for the updated requirements, if you change `^` to `(^1)?` and `1?$` to `(1?$)?` you get pretty much the same as mine. The grouping is different but the basic idea is identical. – tripleee Jan 13 '14 at 16:06
1

The following regex will match any run of zeros where any embedded ones are not adjacent to another one. A leading or trailing one at beginning/end of string is accepted as well.

(^1)?0+(10+)*(1$)?

A test with your example strings yields:

bash$ grep -Eo '(^1)?0+(10+)*(1$)?' <<<10100011110010101
101000
0010101

bash$ grep -Eo '(^1)?0+(10+)*(1$)?' <<<010001001010100
010001001010100
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • They are very similar, but @hsz's answer was submitted before you changed your requirements, so it doesn't match the partial runs. – tripleee Jan 13 '14 at 16:01
0

Search for 11+, i.e. a 1 followed by at least one 1.

sp00m
  • 47,968
  • 31
  • 142
  • 252
0

You can use this, if your regex flavor supports lookarounds:

(?<!1)1(?!1)

(?<!1): not preceded by 1
(?!1): not followed by 1

If your regex flavor doesn't support lookarounds, you can use a capturing group and 2 non capturing groups instead of:

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

(Note that the capturing group is usefull only if you want to catch the offset of the capture with an appropriate function)

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125