使用正则表达式 match 配合模式 \(.*?\) 可以截取第一次出现的括号内文字。调用 regex.match(input, pattern) 获取匹配结果,并通过 .groups[1].value 提取括号内的内容。如果未找到匹配项,则返回空字符串或处理默认值。

如何验证正则表达式匹配逻辑?
通过编写一个简单的控制台程序,输入包含括号的字符串,观察 Match 方法的返回值。重点检查 Success 属性以及 Groups 集合中的索引 1 是否包含预期内容。这能确保在复杂文本中准确捕获第一个括号对。

using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string input = "Hello (World) and (Foo)";
string pattern = @"\(.*?\)";
Match match = Regex.Match(input, pattern);
if (match.Success)
{
// Groups[0] is the full match including parentheses: "(World)"
// Groups[1] is the content inside parentheses: "World"
string result = match.Groups[1].Value;
Console.WriteLine("Result: " + result);
}
else
{
Console.WriteLine("No match found.");
}
}
}
当输入为空或无括号时如何处理?
若输入字符串为 null 或空,Regex.Match 会安全返回失败状态,不会抛出异常。此时应检查 match.Success 来决定后续逻辑。对于无括号的情况,同样返回失败,开发者需根据业务需求提供默认值或提示。
基于程序中某个输入、条件或结果的具体问题
在上述代码中,如果输入是 "Test (A) B (C)",match.Groups[1].Value 的结果是 "A"。这是因为 .*? 是非贪婪匹配,只匹配到第一个右括号即停止。这符合截取“第一次出现”的需求。


















