Regex to Match Binary Numbers

Validate binary number strings in various formats: plain binary digits, 0b-prefixed, or b-suffixed. Matches strings containing only 0s and 1s. Free regex tester.

Regular Expression

/^0b[01]+$|^[01]+b?$/i

Token Breakdown

TokenDescription
^Anchors at the start of the string (or line in multiline mode)
0Matches the literal character '0'
bMatches the literal character 'b'
[01]Character class — matches any one of: 01
+Matches the preceding element one or more times (greedy)
$Anchors at the end of the string (or line in multiline mode)
|Alternation — matches the expression before OR after the pipe
^Anchors at the start of the string (or line in multiline mode)
[01]Character class — matches any one of: 01
+Matches the preceding element one or more times (greedy)
bMatches the literal character 'b'
?Makes the preceding element optional (zero or one times)
$Anchors at the end of the string (or line in multiline mode)

Detailed Explanation

This regex validates binary number representations in multiple common formats. Here is the token-by-token breakdown:

^ — Anchors the first alternative at the start of the string.

0b — Matches the literal prefix 0b used in many programming languages (JavaScript, Python, C) to denote binary literals.

[01]+ — Matches one or more binary digits (0 or 1). This is the actual binary value.

$ — Anchors at the end of the string for the first alternative.

| — Alternation operator separating the two format alternatives.

^ — Anchors the second alternative at the start of the string.

[01]+ — Matches one or more binary digits for plain binary strings or those with a suffix.

b? — Optionally matches a trailing b suffix, used in some assembly languages and documentation to indicate binary notation.

$ — Anchors at the end of the string.

The i flag makes the match case-insensitive, allowing both 0b and 0B prefixes as well as trailing B suffix.

Binary numbers are fundamental in computer science, representing data as sequences of bits. They are used in bitwise operations, hardware programming, network subnet masks, file permissions, and low-level system programming. Common examples include 0b1010 (decimal 10), 11111111 (decimal 255), and 0b00000001 (decimal 1).

This pattern is useful for input validation in developer tools, binary calculators, and educational applications teaching number systems.

Example Test Strings

InputExpected
0b1010Match
11001100Match
1010bMatch
0b1234No Match
102010No Match

Try It — Interactive Tester

//i
gimsuy
No matches found.
Pattern: 19 charsFlags: iMatches: 0

Ctrl+Shift+C to copy regex

Customize this pattern →