如何使用Regex在c#中的文本字符串中提取方括号的内容
如果我有一个如下所示的文本字符串,我怎样才能收集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 matches = Regex.Matches(s.Replace(Environment.NewLine, ""), @"\[([^]]*)\]") .Cast() .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 ]
Regex regex = new Regex(@"\[[^\]]+\]", RegexOptions.Multiline);
关键是要正确地转义正则表达式中使用的特殊字符,例如你可以匹配[
字符这样: @"\["
Regex rx = new Regex(@"\[.+?\]"); var collection = rx.Matches(s);
您将需要关闭方括号,重要的部分是惰性运算符。