Regular expression for numbers

30 Dec 2023

It's easy to find a positive integer number with regular expressions:

[0-9]+

This regex means digits from 0 to 9, repeated one or more times. However, numbers starting with zero are treated as octal in many programming languages, so you may wish to avoid matching them:

[1-9][0-9]*

This regular expression matches any positive integer number starting with a non-zero digit. If you also need to match zero, you can include it as another branch:

[1-9][0-9]*|0

To also accomodate negative integer numbers, you can allow a minus sign before the digits:

-?[1-9][0-9]*|0

Sometimes it's necessary to allow a plus sign as well:

[-+]?[1-9][0-9]*|0

The previous regexes searched the input string for a number. If you need to match a number only discarding anything else, you can add the ^ anchor to match the beginning of the string and the $ anchor to match the end:

^(-?[1-9][0-9]*|0)$

Parentheses are necessary here; without them, the ^ anchor would apply only to the first branch. Another variation of the same regex avoids finding numbers that are part of words, such as 600px or x64:

\b(-?[1-9][0-9]*|0)\b

Things get more complicated if you need to match a fractional number:

\b-?(?:[1-9][0-9]*(?:\.[0-9]+)?|\.[0-9]+|0)\b

Let's break down this regular expression:

For floating-point numbers with an exponent, such as 5.2777e+231, please use:

\b-?(?:[1-9][0-9]*(?:\.[0-9]+)?|\.[0-9]+|0)(?:[eE][+-]?[0-9]+)?\b

Many programming languages support hexadecimal numbers starting with 0x. Here is a regular expression to match them:

0x[0-9a-fA-F]+

Finally, here is a comprehensive regular expression to match floating-point, integer decimal, or hexadecimal numbers:

\b-?(?:[1-9][0-9]*(?:\.[0-9]+)?|\.[0-9]+|0(?:x[0-9a-fA-F]+)?)(?:[eE][+-]?[0-9]+)?\b
Aba Search and Replace screenshot

Stop pasting your data into dubious cloud-based tools. Aba Search and Replace is your Swiss army knife for regular expression search, fast and safe updates across multiple files, and various conversions, with all your data staying on your computer. Built for power users, developers, testers, and analysts. Hand-coded in the EU.

This is a blog about Aba Search and Replace, a tool for replacing text in multiple files.