Reputation: 538
I'm trying to get some named groups(X, Y, Z, W, P, R) from a string and I'm having problems getting the output.
This is the part of the string that has the info I am trying to extract:
[1,1] = Group: 1 Config:
X: -196.999 Y: 1009.999 Z: 210.342
W: 90 P: 0 R: 90
I tried to get the values using the following
@"(?<X>(?<=X:\s*)([+-]?\d*(\.\d+)?))
(?<Y>(?<=Y:\s*)([+-]?\d*(\.\d+)?))
(?<Z>(?<=Z:\s*)([+-]?\d*(\.\d+)?))
(?<W>(?<=W:\s*)([+-]?\d*(\.\d+)?))
(?<P>(?<=P:\s*)([+-]?\d*(\.\d+)?))
(?<R>(?<=R:\s*)([+-]?\d*(\.\d+)?))"
but I didn't get any values.
Only when I use @"(?<X>(?<=X:\s*)([+-]?\d*(\.\d+)?)(?=\s*Y:))"
do I get the correct value for the X Group.
However this
@"(?<X>(?<=X:\s*)([+-]?\d*(\.\d+)?)(?=\s*Y:))
(?<Y>(?<=Y:\s*)([+-]?\d*(\.\d+)?)(?=\s*Z:))"
Also doesn't give me any values.
Eventually matching Config:\s*
will also come into play and when I try this
@"(?<=Config:\s*)(?<X>(?<=X:\s*)([+-]?\d*(\.\d+)?)(?=\s*Y:))"
I don't get a value, but this does
@"(?<=:\s*)(?<X>(?<=X:\s*)([+-]?\d*(\.\d+)?)(?=\s*Y:))"
So, A) I don't understand why I need the lookahead (?=\s*Y:)
to get the value
B) Why does it fail if I add another group?
C) Why am I not matching Config?
Could someone explain to me what I'm doing wrong here?
Upvotes: 2
Views: 53
Reputation: 520908
I suggest a different approach where you just try to find each letter label and its associated float value:
string input = "[1,1] = Group: 1 Config:\nX: -196.999 Y: 1009.999 \nZ: 210.342\nW: 90 P: 0 R: 90";
var re = new Regex(@"\b([A-Z]+):\s*([+-]?\d+(?:\.\d+)?)\b");
MatchCollection matches = re.Matches(input);
for (int mnum = 0; mnum < matches.Count; mnum++)
{
Match match = matches[mnum];
Console.WriteLine("{0}: {1}", match.Groups[1], match.Groups[2]);
}
This prints:
X: -196.999
Y: 1009.999
Z: 210.342
W: 90
P: 0
R: 90
This approach completely avoids the problem of using named capture groups, and instead just tries to match and capture a letters label, followed by a floating point number.
Upvotes: 3