如何使用Regex在c#中提取文本字符串中方括号的内容 [英] How to extract the contents of square brackets in a string of text in c# using Regex
本文介绍了如何使用Regex在c#中提取文本字符串中方括号的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有如下所示的字符串,即使在换行符处经过了换行符,我该如何在c#中的集合中收集括号的内容?
if i have a string of text like below, how can i collect the contents of the brackets in a collection in c# even if it goes over line breaks?
例如...
string s = "test [4df] test [5yu] test [6nf]";
应该给我..
collection [0] = 4df
collection[0] = 4df
collection [1] = 5yu
collection[1] = 5yu
collection [2] = 6nf
collection[2] = 6nf
推荐答案
您可以使用正则表达式和一些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 ]
这篇关于如何使用Regex在c#中提取文本字符串中方括号的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文