JAVASCRIPT
Extracting All Numbers (Integers & Floats) from Text
Discover how to accurately extract all integer and floating-point numbers, including negative values, from any given string using a concise regular expression in JavaScript for data processing.
const text = "Item A costs $19.99, Item B is -5 degrees, and Item C has 123 units.";
const numberRegex = /-?\d+(\.\d+)?/g;
const numbers = text.match(numberRegex);
console.log(numbers);
// Expected output: ["19.99", "-5", "123"]
How it works: This snippet extracts all occurrences of numbers (both integers and floating-point) from a string. The regex `/-?\d+(\.\d+)?/g` matches an optional leading minus sign `-?`, followed by one or more digits `\d+`. It then optionally matches a decimal point `\.` followed by one or more digits `\d+`, enclosed in a non-capturing group `(\.\d+)?`. The `g` flag ensures all matches are returned.