There's plenty of these questions on SO, but I'm finding none specific to this case by extracting a vector coordinates to integer values.
I'm parsing the current string:
"AT (1,1) ADDROOM RM0001"
I need to get the numbers between (#,#) and store them as integers.
One solution I tried was get the index of the first '('. Read in the string until a comma is met, and then read again until the last ')' is met. Another solution I tried was find the ',' and get the string prior and after it before meeting a parenthesis.
I keep feeling this is error-prone though. I feel there's an easier way to do this if reading from the string. I was researching on Regex.
This is the regex you need:
\((-?\d+)\s*,\s*(-?\d+)\)
You can use it like this:
var match = Regex.Match("some string (1234, -5678)", @"\((-?\d+)\s*,\s*(-?\d+)\)")
var x = match.Groups[1].Value;
var y = match.Groups[2].Value;
x and y will be the two components of the vector.
Explanation:
\( open parenthesis(-?\d+) first capturing group that captures the first component of the vector. The - is optional (so both positive and negative integers are matched) followed by 1 or more digits (\d). This same thing appears again later in the regex to capture the second component\s* this allows any number of whitespace between the numbers and the comma\) close parenthesisFor a lower level explanation, go to https://regex101.com/r/PnwBJS/1 and look at the "explanation" section.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With