Regular expression for numbers

30 Dec 2023

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


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:


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:


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


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


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:


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:


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


Let's break down this regular expression:

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


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


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

Aba Search and Replace screenshot

Replacing text in several files used to be a tedious and error-prone task. Aba Search and Replace solves the problem, allowing you to correct errors on your web pages, replace banners and copyright notices, change method names, and perform other text-processing tasks.

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