温馨提示×

怎么使用c#正则表达式获取括号内容

小亿
318
2023-07-10 21:20:42
栏目: 编程语言

您可以使用以下代码来使用C#正则表达式获取括号内容:

using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string input = "这是一个示例(带括号的)字符串";
// 使用正则表达式获取括号内容
string pattern = @"\((.*?)\)";
MatchCollection matches = Regex.Matches(input, pattern);
// 输出括号内容
foreach (Match match in matches)
{
Console.WriteLine(match.Groups[1].Value);
}
}
}

在上面的代码中,我们使用正则表达式 @"\((.*?)\)" 来匹配括号中的内容。这个正则表达式的含义是:匹配一个左括号 (,然后匹配任意数量的字符(非贪婪模式),最后匹配一个右括号 )。使用 Regex.Matches() 方法来获取所有匹配项,并使用 match.Groups[1].Value 来获取括号中的内容。

希望能帮到您!

0