Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a regular expression (C#) to identify a string of eight 1's & 0's

Tags:

c#

regex

I'm trying to build a regex to determine if a string contains a byte of binary digits, ex. 10010011.

I believe that [0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1] would work, but I'm sure theres a more efficient way of doing it, and being new to regular expressions, I'm not sure what that is.

like image 762
Doug S. Avatar asked Feb 18 '11 20:02

Doug S.


3 Answers

That would be this one

[01]{8}

This [0-1] is not technically wrong, but "0-1" is hardly a range, so you can drop the dash.

like image 168
Tomalak Avatar answered Oct 27 '22 16:10

Tomalak


If it needs to be exactly 8 (no more/less), use this:

@"(?<![01])([01]{8})(?![01])"

If you don't want to match something like "abc01010101xyz", use this:

@"\b[01]{8}\b"

If you want to match all 8-bit strings anywhere in the input, use this:

@"[01]{8}"

Be aware that if you feed the last pattern an input like 1111111100000000, you're going to get a result set like:

11111111
11111110
11111100
11111000
...
00000000
like image 11
Justin Morgan Avatar answered Oct 27 '22 17:10

Justin Morgan


I believe [01]{8} should do it.

like image 5
Mark Avenius Avatar answered Oct 27 '22 16:10

Mark Avenius