如何正确地访问捕获组在C#中的正则表达式的值? [英] How to properly access the value of a capture group in C# regex?
本文介绍了如何正确地访问捕获组在C#中的正则表达式的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
var r = new Regex(@"_(\d+)$");
string new_name = "asdf_1";
new_name = r.Replace(new_name, match =>
{
Console.WriteLine(match.Value);
return match.Value;
//return (Convert.ToUInt32(match.Value) + 1).ToString();
});
//Console.WriteLine(new_name);
}
}
我期待 match.Value
是 1
,但它打印成 _1
。我在做什么错了?
I expect match.Value
to be 1
, but it is printing as _1
. What am I doing wrong?
推荐答案
你得到整个匹配的值
- 你只想要一个组(第1组),你可以通过的 组
属性和 GroupCollection
索引:
You're getting the value of the whole Match
- you only want a single group (group 1) which you can access via the Groups
property and the GroupCollection
indexer:
Console.WriteLine(match.Groups[1]);
这篇关于如何正确地访问捕获组在C#中的正则表达式的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文