gpt4 book ai didi

c# - 括号不捕获 c# 正则表达式组

转载 作者:行者123 更新时间:2023-11-30 14:22:32 25 4
gpt4 key购买 nike

尝试使用以下代码从字符串中提取 nameid:

Regex.Matches
"id: 123456, name: some dude",
@"^id: (?<id>\d+), name: (?<name>[a-z]+(\s[a-z]+)?)"
);

但是group和captures的个数都是1,没有命名的captures。我错过了什么?

编辑:找到了答案(谢谢大家!)但为了将来引用,事实证明这是因为我完全误解了 API 并且错误地访问了匹配项。我在做这样的事情:

Console.WriteLine(matches.Count); // 1
foreach( Group g in matches ) {
Console.WriteLine(g.Captures.Count); //1
foreach( Capture c in g.Captures ) {
Console.WriteLine(c.Value); // The whole string
}
}

但现在我知道得更多了!

最佳答案

这很好用

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);
}

当 .Net Fiddle 再次工作时 you can demo it here


为了完整性

Regex.Match Method (String)

Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor.

Regex.Matches Method

Searches an input string for all occurrences of a regular expression and returns all the matches.

Match.Groups Property

Gets a collection of groups matched by the regular expression. Groups can then be retrieved from the GroupCollection object

GroupCollection.Item Property (String)

Enables access to a member of the collection by string index. GroupName can be either the name of a capturing group that is defined by the (?<name>) element in a regular expression, or the string representation of the number of a capturing group that is defined by a grouping construct

关于c# - 括号不捕获 c# 正则表达式组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49185353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com