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

Gra*_*ant 8 c# regex match

如果我有一个如下所示的文本字符串,我怎样才能收集c#中集合中括号的内容,即使它超过了换行符?

例如...

string s = "test [4df] test [5yu] test [6nf]";
Run Code Online (Sandbox Code Playgroud)

应该给我..

集合[0] = 4df

集合[1] = 5yu

集合[2] = 6nf

Mar*_*ers 18

你可以用正则表达式和一些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);
Run Code Online (Sandbox Code Playgroud)

输出:

4df
5yu
6nf
Run Code Online (Sandbox Code Playgroud)

这是正则表达式的含义:

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