如果我有一串如下所示的文本,我如何在 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/