Question

{(1,2),(3,4)};

How can I check that an input like the above is a set (between '{' and '}') of two pairs (integer values between '(' and ')'. Three commas, as above, must be used. My guess is that maybe some kind of search (don't know which) on a character array for the correct symbols would be best but is there any faster way?

Bear in mind that integer values could be much huger than 1, 2, 3 etc, and negative.

Was it helpful?

Solution

If this is not performance critical, you can use a quick and dirty regex.

  • -?\d+ matches a digit sequence of any length (i.e. 1 or more digits), optionally preceded by a negative sign
  • Braces { } and parentheses ( ) are special characters in a regex, so they must be escaped (\{, etc.)
  • My assumption is that no whitespace is allowed. If this is not true, you will need to modify the regex to include optional whitespace \s* (zero or more whitespace characters) in any place where it is allowed.

The final regex should be as follows: \{\(-?\d+,-?\d+\),\(-?\d+,-?\d+\)\}

If you also need to capture any of the digit values, you can add capturing parentheses.

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