justyy
justyy

Reputation: 6041

How to get the matched sub-groups in C# using Regex?

I have a string:

{Lower Left  (  460700.000, 2121200.000)}

and here is my code:

    var pat = @"Lower Left\s*\(\s*[\d\.]+\,(\s)*[\d\.]+\)";
    var r = new Regex(pat, RegexOptions.IgnoreCase);
    var m = r.Match(s);

The m.Groups[0] now equals:

{Lower Left  (  460700.000, 2121200.000)}

But I want to get the coordinate strings in two variables, e.g. X and Y. how to do it?

Upvotes: 0

Views: 68

Answers (2)

NoName
NoName

Reputation: 8025

You could do like this:

string s = "{Lower Left  (  460700.000, 2121200.000)}";

var pat = @"Lower Left\s*\(\s*(\d+\.\d+)\,\s*(\d+\.\d+)\)";
var r = new Regex(pat, RegexOptions.IgnoreCase);
var m = r.Match(s);
Console.WriteLine(m.Groups[1]); // first number
Console.WriteLine(m.Groups[2]); // second number

If your number may or may not contain ., you can use:

string s = "{Lower Left  (  460700.000, 2121200.000)}";

var pat = @"Lower Left\s*\(\s*(\d+(?:\.\d+)?)\,\s*(\d+(?:\.\d+)?)\)";
var r = new Regex(pat, RegexOptions.IgnoreCase);
var m = r.Match(s);
Console.WriteLine(m.Groups[1]);
Console.WriteLine(m.Groups[2]);

This will accept this number: 123456 (no dot), 123.456 (one dot inside), but not 123.456.7 (two dot) or 1234. (dot at the end).

Upvotes: 1

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37123

The first group allways returns the entire match, whilst the indexed ones contain your actual values for the matching groups. So you need m.Groups[1] and m.Groups[1] accordingly.

You can also name your groups:

@"Lower Left\s*\(\s*(?<X>\d+\.\d+),(\s)*(?<Y>\d+\.\d+)\)";

Where (?<identifier>anyPattern) means build a matching-group which is named identifier and has the pattern given by anyPattern. Allowing you to access them like this:

m.Groups["X"]
m.Groups["Y"]

The square-brackets ([]) are also not needed at all as this would mean "either a number od digits (\d+), or a dot", not "a number of digits followed by a dot followed by a number of digits".

Upvotes: 1

Related Questions