6.3. Binary Numbers
Problem
You want to find binary numbers in a larger body of text, or check whether a string variable holds a binary number.
Solution
Find a binary number in a larger body of text:
\b[01]+\b
| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Check whether a text string holds just a binary number:
\A[01]+\Z
| Regex options: None |
| Regex flavors: .NET, Java, PCRE, Perl, Python, Ruby |
^[01]+$
| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python |
Find a binary number with a 0b prefix:
\b0b[01]+\b
| Regex options: Case insensitive |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Find a binary number with a B suffix:
\b[01]+B\b
| Regex options: Case insensitive |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Find a binary byte value or 8-bit number:
\b[01]{8}\b| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Find a binary word value or 16-bit number:
\b[01]{16}\b| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Find a string of bytes (i.e., a multiple of eight bits):
\b(?:[01]{8})+\b| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Discussion
All these regexes use techniques explained in the previous two
recipes. The key difference is that each digit is now a 0 or a 1. We easily match that
with a character class that includes just those two characters: ‹[01]›.
See Also
All the other recipes in this chapter show more ways ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access