Regex for Binary number with 0b prefix
Binary literal: 0b101010.
The Binary number with 0b prefix regex is ^0[bB][01]+$ — copy it below, or open it in the explainer for a token-by-token breakdown.
The pattern
^0[bB][01]+$
Token-by-token breakdown
Every part of the pattern, left to right:
| Token | Meaning |
|---|---|
^ | start of string (or line in multiline mode) |
0 | literal text “0” |
[bB] | any of: “b”, “B” |
[01]+ | one or more: any of: “0”, “1” |
$ | end of string (or line in multiline mode) |
About this pattern
Number patterns appear constantly in form validation, log parsing, and data extraction. Regex is great for matching the shape but limited for semantic checks (range validation, mathematical constraints).
Quick usage in different languages
This exact pattern — with the correct escaping and idioms for each language:
- JavaScript:
/^0[bB][01]+$/.test(value) - Python:
re.match(r"^0[bB][01]+$", value) - Java:
Pattern.compile("^0[bB][01]+$").matcher(value).matches() - C# / .NET:
Regex.IsMatch(value, @"^0[bB][01]+$") - Go:
regexp.MustCompile(`^0[bB][01]+$`).MatchString(value) - Ruby:
/^0[bB][01]+$/.match?(value) - PHP:
preg_match('~^0[bB][01]+$~', $value)
The explainer’s Code tab regenerates these for any pattern you paste, and the downloadable cheat sheet bundles the breakdown, all seven snippets, and the pitfalls below onto one printable page.
Common pitfalls
- Anchored to the whole string. This pattern uses ^ and $, so it requires the entire input to match. To find it inside a longer text, drop the anchors and use the global (g) flag.
- Validate beyond format. Matching the format doesn't guarantee the value is real. Confirm the binary number with 0b prefix against a source of truth (database, API, or checksum) where it matters.
Related patterns
More patterns in the Numbers & text category:
- Hex number with 0x prefix
- Octal number with 0o prefix
- Positive integer
- Ordinal number
- Signed integer
- Roman numerals
See also
Browse all 300 patterns in the library, or open this regex in the interactive explainer to see a token-by-token breakdown, test against custom input, and generate code in seven languages.