c# - 如何解析这个?

标签 c# regex

我需要解析出具有以下结构的字符串

x:{a,b,c,}, y:{d,e,f} 等

所有条目都是数字,所以它看起来像这样

411:{1,2,3},241:{4,1,2} 等

忘记提及:{} 之间的逗号分隔条目数没有上限,但必须至少有一个条目。

  1. 我需要获得唯一的列表 : 之前的数字,在上面的例子中 411,241

这可以用正则表达式完成吗?如何做?

最佳答案

正则表达式:

(?<1>[\d]+):{(?<2>\d+),(?<3>\d+),(?<4>\d+)}

对于数据:

411:{1,2,3},241:{4,1,2},314:{5,6,7}

将产生以下匹配/组集合:

Match 0
Group 0: 411:{1,2,3}
Group 1: 411
Group 2: 1
Group 3: 2
Group 4: 3

Match 1
Group 0: 241:{4,1,2}
Group 1: 241
Group 2: 4
Group 3: 1
Group 4: 2

Match 2
Group 0: 314:{5,6,7}
Group 1: 314
Group 2: 5
Group 3: 6
Group 4: 7

您可以使用以下代码:

string expression = "(?<1>[\d]*):{(?<2>\d),(?<3>\d),(?<4>\d)}";
string input = "411:{1,2,3},241:{4,1,2},314:{5,6,7}";

Regex re = new Regex(expression, RegexOptions.IgnoreCase);

MatchCollection matches = re.Matches(input);

for (int i = 0; i < matches.Count; i++)
{
Match m = matches[i];
// for i==0
// m.groups[0] == 411:{1,2,3}
// m.groups[1] == 411
// m.groups[2] == 1
// m.groups[3] == 2
// m.groups[4] == 4
}

更新 无法使用纯正则表达式和列表中可变数量的项目 - 也许其他人可以在这里插话。一个简单的解决方案是:

string expression = "(?<1>[\d]+):{(?<2>[\d,?]+)}";
string input = "411:{1,2,3,4,5},241:{4,1,234}";

Regex re = new Regex(expression, RegexOptions.IgnoreCase);

MatchCollection matches = re.Matches(input);

for (int i = 0; i < matches.Count; i++)
{
Match m = matches[i];
// for i==0
// m.groups[0] == "411:{1,2,3}"
// m.groups[1] == "411"
// m.groups[2] == "1,2,3"
int[] list = m.Groups[1].Split(",");
// now list is an array of what was between the curly braces for this match
}

上面的匹配列表:

Match 0
Group 0: 411:{1,2,3,4,5}
Group 1: 411
Group 2: 1,2,3,4,5

Match 1
Group 0: 241:{4,1,234}
Group 1: 241
Group 2: 4,1,234

关于c# - 如何解析这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1631716/

相关文章:

c# - 无法在 Windows 10 移动版上部署

c# - 有没有办法对 Azure Powershell Cmdlet 进行子类化,或者类似的方法?

c# - C# 中的 Iif 等价物

regex - 用 r 中正确的位数替换数字

c# - 正则表达式 (.NET) - 如何匹配字符串末尾包含可变数字的模式?

c# - LINQ-所有条件

c# - 无法将类型为 'System.Data.DataRowView' 的对象转换为类型 'System.Data.DataRow'

objective-c - 单独 key :value-string to NSDictionary

python - 使用正则表达式提取所有 html 属性

html - 需要最佳实践帮助或 RegEx 建议来创建 Image Sprite 映射到 CSS