Extract negative value from regex

Viewed 44

The Regex is:

pattern = new RegExp(/coordinates\([-+]?(\d+(\.\d+)?) [-+]?(\d+(\.\d+)?)\)/i)

Test:

pattern.exec('coordinates(1.5421245 23.243545689)')

results:

["coordinates(1.5421245 23.243545689)", "1.5421245", ".5421245", "23.243545689", ".243545689", index: 0, input: "coordinates(1.5421245 23.243545689)", groups: undefined]

and I can extract the points from index 1 and 3 as 1.5421245 and 23.243545689.

But for one or more negative numbers, it is not extracting the correct numbers.

Ex. pattern.exec('coordinates(1.5421245 -23.243545689)') returns

["coordinates(1.5421245 -23.243545689)", "1.5421245", ".5421245", "23.243545689", ".243545689", index: 0, input: "coordinates(1.5421245 -23.243545689)", groups: undefined]
1 Answers

You can move the open parenthesis to the left to also include the plus or minus sign, and use

/coordinates\(([-+]?\d+(?:\.\d+)?) ([-+]?\d+(?:\.\d+)?)\)/i
/coordinates\(([-+]?\d+(?:\.\d+)?)\s+([-+]?\d+(?:\.\d+)?)\)/i

See the regex demo. Note that now, all your required values are in Group 1 and Group 2, no redundant groups since the (\.\d+)? (capturing group) is now a non-capturing group, (?:\.\d+)?.

The \s+ pattern matches one or more whitespaces, which can be useful if the text is not always formatted with a single space.

Related