rph020798 rph020798 - 1 month ago 11
C++ Question

Regex expression to match multiple coordinates separated by spaces

I am trying to learn regex for my project I am working on to use it for input validation because I have been told that using regex is one of the best ways to do input validation.

So, I am trying to make sure a string contains an unknown number of coordinates which are separated by a space. An example of what the input will look like is

2,2 23.45,6 45,21.65 2,2
I'm not sure if it matters, but the last coordinate will always match the first. There can't be any symbols or extraneous spaces or commas. Only a decimal numbers split with a comma, followed by a space or an endline character.

I realize that this is probably quite a complex expression, and I am pretty much jumping into regex blind, so any help with this would be really appreciated. I am programming in c++ if that changes anything. Thanks.

EDIT:

I had forgotten about the possibility of negative numbers and newline characters. I also accept negative numbers and newline characters in the input.
So the input
-2.3,2 34,-2 -2.3,2\n
is acceptable. Thank you to everyone so far for the help.

Answer

You can try this regex:

^\d+(?:\.\d+)?,(?:\d+(?:\.\d+)? \d+(?:\.\d+)?,)*\d+(?:\.\d+)?$

Demo here:

Regex101

Note: The regex \d+(?:\.\d+)? matches any number, possibly having a decimal component. The ?: inside the parenthesis marks the quantity as a non capture group. This tells the regex engine to not capture what is inside, as we don't want to actually capture anything here. This possibly will result in a more efficient regex.