Regular Expressions Cookbook, 2nd Edition
by Steven Levithan
Published by
O'Reilly Media, Inc., 2012
and
Tags
| 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 |
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]›.
All the other recipes in this chapter show more ways of matching different kinds of numbers with a regular expression.
Techniques used in the regular expressions in this recipe are discussed in Chapter 2. Recipe 2.3 explains character classes. Recipe 2.6 explains word boundaries. Recipe 2.12 explains repetition.