I'm having trouble writing a correct REGEX and parsing the string in C#. The string I get an input is:
{EnemyMove X:7 Y:8}
I need to digits the follow X and the digits that follow Y, the range is 0-10. Tried the code below, but the regex is incorrect and I get an incorrect result.
I need to run it twice, once to get the digits adjacent to X and second time for the digits after Y.
string str = "{EnemyMove X:9 Y:10}";
var regex_sp_chrs = new Regex("/X:.*?(\d+)/");
regex_sp_chrs.Matches(str );
Expected output - 9 10
Thanks in advance.
If you want to restrict the numbers to 0-10 range, replace \\d+
with 10|\\d
:
X:(?<X>10|\d)\s+Y:(?<Y>10|\d)
See demo
So, you need to remove the delimiters (leading/trailing /
) and add the Y
part.
Group X
will contain the digits after X
and Group Y
will contain the digits after Y
.
C# demo :
var str = "{EnemyMove X:9 Y:10}";
var regex_sp_chrs = new Regex(@"X:(?<X>10|\d)\s+Y:(?<Y>10|\d)");
var ms = regex_sp_chrs.Matches(str);
foreach (Match m in ms)
Console.WriteLine(string.Format("{0} - {1}",
m.Groups["X"].Value,
m.Groups["Y"].Value));
It will output 9 - 10
, 9
is the m.Groups["X"].Value
and 10
is the m.Groups["Y"].Value
.
If you know {EnemyMove
is static (always present as a literal before X
), add it to the regex to make it safer (ie @"{EnemyMove\\s+X:(?<X>\\d+)\\s+Y:(?<Y>\\d+)"
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.