C# 不捕获c正则表达式组的括号
尝试使用以下代码从字符串中提取名称和id:C# 不捕获c正则表达式组的括号,c#,.net,regex,C#,.net,Regex,尝试使用以下代码从字符串中提取名称和id: Regex.Matches "id: 123456, name: some dude", @"^id: (?<id>\d+), name: (?<name>[a-z]+(\s[a-z]+)?)" ); 但现在我知道了 当正则表达式看起来正常时,查找匹配项的方式可能有问题: Regex.Matches( "id: 123456, name: some dude", @"^id: (?<id&
Regex.Matches
"id: 123456, name: some dude",
@"^id: (?<id>\d+), name: (?<name>[a-z]+(\s[a-z]+)?)"
);
但现在我知道了 当正则表达式看起来正常时,查找匹配项的方式可能有问题:
Regex.Matches(
"id: 123456, name: some dude",
@"^id: (?<id>\d+), name: (?<name>[a-z]+(\s[a-z]+)?)"
)[0].Groups.Cast<Group>().Skip(2).Select(x => new {x.Name, x.Value})
产生:
Name Value
id 123456
name some dude
如果您只需要一个-Regex.Matches…[0].Groups[2]或.Groups[id]
请注意,您的代码使用返回所有匹配项的匹配项,如果您只希望使用单一匹配项,则使用如所示的匹配项即可
String sample = "id: 123456, name: some dude";
Regex regex = new Regex(@"^id: (?<id>\d+), name: (?<name>[a-z]+(\s[a-z]+)?)");
Match match = regex.Match(sample);
if (match.Success)
{
Console.WriteLine(match.Groups["id"].Value);
Console.WriteLine(match.Groups["name"].Value);
}
当.NETFiddle再次工作时
为了完整性
在指定的输入字符串中搜索
正则表达式构造函数中指定的正则表达式
在输入字符串中搜索正则表达式的所有匹配项
并返回所有匹配项
获取由正则表达式匹配的组的集合。组
然后可以从GroupCollection对象检索
允许通过字符串索引访问集合的成员。
GroupName可以是已定义的捕获组的名称
由?元素,或字符串
表示由定义的捕获组的编号
分组结构
您应该使用Match,而不是Matches,并且在正则表达式中使用非捕获组?:
^id:\s?\d+,\n名称:\s?[\w\s]+?工作正常。。。你能展示一下你是如何尝试访问这些组的吗?
String sample = "id: 123456, name: some dude";
Regex regex = new Regex(@"^id: (?<id>\d+), name: (?<name>[a-z]+(\s[a-z]+)?)");
Match match = regex.Match(sample);
if (match.Success)
{
Console.WriteLine(match.Groups["id"].Value);
Console.WriteLine(match.Groups["name"].Value);
}
String input = "id: 123456, name: some dude";
var output = Regex.Match(input, @"^id: (?<id>\d+), name: (?<name>.+)");
System.Console.WriteLine(output.Groups["id"]);
System.Console.WriteLine(output.Groups["name"]);
123456
some dude