且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Regex在c#中提取文本字符串中方括号的内容

更新时间:2023-11-13 21:15:04

您可以使用正则表达式和一些Linq来做到这一点.

You can do this with regular expressions, and a bit of Linq.

    string s = "test [4df] test [5y" + Environment.NewLine + "u] test [6nf]";

    ICollection<string> matches =
        Regex.Matches(s.Replace(Environment.NewLine, ""), @"\[([^]]*)\]")
            .Cast<Match>()
            .Select(x => x.Groups[1].Value)
            .ToList();

    foreach (string match in matches)
        Console.WriteLine(match);

输出:

4df
5yu
6nf

正则表达式的含义如下:

Here's what the regular expression means:

\[   : Match a literal [
(    : Start a new group, match.Groups[1]
[^]] : Match any character except ]
*    : 0 or more of the above
)    : Close the group
\]   : Literal ]