简体   繁体   English

C#使用正则表达式解析字符串 - 与字母相邻的数字

[英]C# parse string using regex - number adjacent to letter

I'm having trouble writing a correct REGEX and parsing the string in C#. 我在编写正确的REGEX并在C#中解析字符串时遇到了麻烦。 The string I get an input is: 我得到输入的字符串是:

{EnemyMove X:7 Y:8} {EnemyMove X:7 Y:8}

I need to digits the follow X and the digits that follow Y, the range is 0-10. 我需要数字跟随X和跟随Y的数字,范围是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. 我需要运行它两次,一次得到X附近的数字,第二次得到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 预期产出 - 9 10

Thanks in advance. 提前致谢。

If you want to restrict the numbers to 0-10 range, replace \\d+ with 10|\\d : 如果要将数字限制为0-10范围,请将\\d+替换为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. 因此,您需要删除分隔符(前导/尾随/ )并添加Y部分。

Group X will contain the digits after X and Group Y will contain the digits after Y . 集团X后,将包含数字X和集团Y会后包含数字Y

在此输入图像描述

C# demo : 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 . 它会输出9 - 109m.Groups["X"].Value10m.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+)" ). 如果您知道{EnemyMove是静态的(在X之前始终作为文字出现),请将其添加到正则表达式以使其更安全(即@"{EnemyMove\\s+X:(?<X>\\d+)\\s+Y:(?<Y>\\d+)" )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM