Question

So I have a javascript program that solves for 1 variable. I'm coming to a roadblock when selecting numbers that DON'T have a variable associated with them.

Here is my current regex expression:

(\+|-)?([0-9]+)(\.[0-9]+)?(?![a-z])

takes input like 15000.53=1254b+21 and returns [15000.53, 125, +21], when it should return [15000.53, +21] (yes, the + is supposed to be there)

I know why it is happening. The number of digits is optional so the function can handle large numbers and floats, but they are optional, so it is hard to make sure the entire number is selected. The result of this is selecting all the digits of the number EXCEPT the one directly next to the variable.

Anyone know of a way for the number of digits to stay optional, yet still make sure a variable doesn't follow the number? Thanks!

var reg = (\+|-)?([0-9]+)(\.[0-9]+)?(?![a-z]);
var numbers = [];
var equation = '15000.53=1254b+21';
while (aloneInt = reg.exec(side[0])) {
    numbers.push(aloneInt[0]);
}
Was it helpful?

Solution

Try the following expression:

(?![+-]?[0-9.]+[a-z])(\+|-)?([0-9]+)(\.[0-9]+)?

The added negative lookahead (?![+-]?[0-9.]+[a-z]) makes sure there isn't one or more optionally signed floating point numbers that are followed by a letter from the alphabet.

In other words, it makes sure there isn't a number followed by a variable name, then it matches the number.

Regex101 Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top