As far as regexes go, this case seems rather trivial, but I know regex can be hard to wrap your head around, so I'll go over it in detail.
In regex, a numeric value can be represented by \d
. I'm assuming you want to capture coordinates larger than 9 too though, so we'll use \d+
to capture multiple numbers.
For the rest, the comma is just a literal, and it doesn't have any special function in regex when not used inside specific structures. Unescaped brackets become capture groups, so literal brackets need to be escaped by putting a \
before them. You need two capture groups here, one around each of your numbers.
With that, your (#,#)
, as regex, will become \((\d+),(\d+)\)
. Literal opening bracket, a capture group with one or more number characters in it, a literal comma, another number characters capture group, and finally, the literal closing bracket.
Test it out online
Then, it's just a matter of getting the capture groups and parsing them as integers. Note that there's no need for TryParse
since we are 100% sure that the contents of these groups are one or more numeric symbols, so if the regex matches, the parse will always succeed.
String str ="AT (1,1) ADDROOM RM0001";
// Double all backslashes in the code, or prefix the quoted part with @
Regex coords = new Regex("\\((\\d+),(\\d+)\\)");
MatchCollection matches = coords.Matches(str);
if (matches.Count > 0)
{
Int32 coord1 = Int32.Parse(matches[0].Groups[1].Value);
Int32 coord2 = Int32.Parse(matches[0].Groups[2].Value);
// Process the values...
}
Of course, if you have multiple matches to process, you can use a foreach
to loop over the contents of the MatchCollection
.
[edit]
As pointed out by Sweeper, if you want to capture both positive and negative numbers, the capture groups should become (-?\d+)
. The question mark indicates an optional component, meaning there can be either 0 or 1 of the literal -
character that's before it. This would give:
\((-?\d+),(-?\d+)\)
And if you want to allow spaces between these coordinates and the brackets / commas, you'll need to add some \s*
between the groups, brackets and commas too. The *
is a modifier (like +
and ?
) which indicates zero or more occurrences of the element before it. \s
is shorthand for "whitespace", just like \d
is for numbers.
This more lenient version would be
\(\s*(-?\d+)\s*,\s*(-?\d+)\s*\)