正则表达式将[A] [B]解析为A和B.

时间:2012-07-09 15:47:16

标签: c# regex

我正在尝试将以下字符串分隔为具有正则表达式的单独行

[property1=text1][property2=text2] 

,所需的结果应为

property1=text1
property2=text2

这是我的代码

string[] attrs = Regex.Split(attr_str, @"\[(.+)\]");

结果不正确,可能做错了

enter image description here

应用建议的答案后,

更新:。现在它显示空格和空字符串

enter image description here

4 个答案:

答案 0 :(得分:5)

.+是一个贪婪的比赛,所以它尽可能地抓住。

使用

\[([^]]+)\]

\[(.+?)\]

在第一种情况下,不允许匹配],因此“尽可能”变得更短。第二个使用非贪婪的比赛。

答案 1 :(得分:4)

你的圆点也抓住了牙箍。你需要排除大括号:

\[([^]]+)\]

[^]]匹配除了括号之外的任何字符。

答案 2 :(得分:2)

尝试添加'lazy'说明符:

Regex.Split(attr_str, @"\[(.+?)\]"); 

答案 3 :(得分:2)

尝试:

var s = "[property1=text1][property2=text2]";
var matches = Regex.Matches(s, @"\[(.+?)\]")
    .Cast<Match>()
    .Select(m => m.Groups[1].Value);
相关问题