Skip to content
Advertisement

Regular expression to find any number in a string

What’s the notation for any number in re? Like if I’m searching a string for any number, positive or negative. I’ve been using d+ but that can’t find 0 or -1

Advertisement

Answer

Searching for positive, negative, and/or decimals, you could use [+-]?d+(?:.d+)?

JavaScript

This isn’t very smart about leading/trailing zeros, of course:

JavaScript

Edit: Corrected the above regex to find single-digit numbers.

If you wanted to add support for exponential form, try [+-]?d+(?:.d+)?(?:[eE][+-]?d+)?:

JavaScript
Advertisement