如何使用正则表达式在C#中提取文本字符串中方括号内的内容

bluesky1年前 ⋅ 221 阅读

ChatGPT的回答仅作参考:

在C#中,可以使用正则表达式的`Match`方法来提取文本字符串中方括号内的内容。下面是一个示例代码:

```csharp
using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string input = "这是一个[示例]文本字符串[用于]提取方括号内的内容";
        string pattern = @"\[(.*?)\]";

        MatchCollection matches = Regex.Matches(input, pattern);

        foreach (Match match in matches)
        {
            string content = match.Groups[1].Value;
            Console.WriteLine(content);
        }
    }
}
```

在上面的示例中,我们使用了正则表达式模式`@"\[(.*?)\]"`来匹配方括号内的内容。其中:

- `\[`和`\]`分别匹配左右方括号;
- `(.*?)`使用非贪婪模式匹配方括号内的任意字符,并将匹配结果保存在第一个捕获组中。

然后,我们使用`Regex.Matches`方法来获取所有匹配的结果,并使用`match.Groups[1].Value`来获取方括号内的内容。最后,我们通过循环打印出提取到的内容。

运行上述代码,输出结果为:

```
示例
用于
```

全部评论: 0

    相关推荐