C#正则表达式获取组名,按照组名输出匹配内容

最近写了个正则表达式匹配的工具,可以按照组名输出匹配内容,还是挺方便的,代码留存一下,以后用的话,直接copy了。

            Regex regex = new Regex(this.textBoxRegex.Text);
            Match result = regex.Match(this.textBoxText.Text);
           
            if (result.Success)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var groupName in regex.GetGroupNames())
                {
                    sb.AppendLine(String.Format("<{0}>{1}", groupName,
                        result.Groups[regex.GroupNumberFromName(groupName)].Value));
                }
                this.textBoxMatchResult.Text = sb.ToString();
            }
            else
            {
                MessageBox.Show("匹配失败");
            }

就一个WinForm的小函数,搞C#的应该一看就明白了吧。

原文地址:https://www.cnblogs.com/jasondan/p/3913407.html