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

标签 c# regex match

如果我有一串如下所示的文本,我如何在 C# 中收集集合中括号的内容,即使它超过了换行符?

例如...

string s = "test [4df] test [5yu] test [6nf]";

应该给我..

集合[0] = 4df

收藏[1] = 5yu

集合[2] = 6nf

最佳答案

您可以使用正则表达式和一点 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

正则表达式的含义如下:

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

关于c# - 如何使用正则表达式在c#中提取文本字符串中方括号的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1811183/

相关文章:

JavaScript。如何从字符串中提取 URI 编码的电子邮件?

javascript - 正则表达式 - 匹配 0 次或 1 次

R 将数据框中的字符串更改为数字

c# - 使用javascript选中和取消选中转发器控件中的复选框?

c# - 将所有查询与 Elasticsearch 索引匹配

c# - 将 Dictionary<string, class> 转换为 IDictionary<string, interface>

php - 搜索查询中的匹配问题

c# - 在远程服务器上启动 GUI 应用程序

python - `re` 模块匹配Python3中两对括号之间的文本

python - 在 Python 中将列表项与大文件中的行匹配的最有效方法是什么?