Regex to Match Octal Numbers
Validate octal number strings with leading zero or 0o prefix. Matches numbers using only digits 0-7 in standard octal notation. Free online regex pattern tester.
Regular Expression
/^0o?[0-7]+$/i
Token Breakdown
| Token | Description |
|---|---|
| ^ | Anchors at the start of the string (or line in multiline mode) |
| 0 | Matches the literal character '0' |
| o | Matches the literal character 'o' |
| ? | Makes the preceding element optional (zero or one times) |
| [0-7] | Character class — matches any one of: 0-7 |
| + | Matches the preceding element one or more times (greedy) |
| $ | Anchors at the end of the string (or line in multiline mode) |
Detailed Explanation
This regex validates octal (base-8) number representations. Here is the token-by-token breakdown:
^ — Anchors the match at the start of the string, ensuring the entire input is validated.
0 — Matches a literal zero at the beginning. In most programming languages, a leading zero indicates an octal literal. This is the required first character.
o? — Optionally matches the letter o after the leading zero. The 0o prefix is used in modern JavaScript (ES6+), Python 3, and other languages to explicitly denote octal numbers. The question mark makes it optional to also accept the traditional C-style format where a bare leading zero indicates octal.
[0-7]+ — Matches one or more octal digits. The valid digits in base-8 are 0 through 7 only. Digits 8 and 9 are not valid in octal notation and would cause this match to fail.
$ — Anchors the match at the end of the string.
The i flag makes the match case-insensitive, allowing both 0o and 0O prefixes.
Octal numbers are historically important in computing because octal digits map cleanly to groups of three binary bits. They are commonly used for Unix file permissions (like 0755 for rwxr-xr-x), legacy C code, and some embedded systems. Examples include 0o777 (decimal 511), 0644 (decimal 420 for file permissions), and 0o10 (decimal 8).
This pattern is useful for input validation in permission calculators, number base converters, and programming education tools.
Example Test Strings
| Input | Expected |
|---|---|
| 0o777 | Match |
| 0644 | Match |
| 0o10 | Match |
| 0o89 | No Match |
| 777 | No Match |
Try It — Interactive Tester
11 charsFlags: iMatches: 0Ctrl+Shift+C to copy regex