如何创建一个将字符串格式分割成字符串数组的RegEx? 字符串应该有分号和值分隔,如果没有','分隔键值,它不应该通过测试RegEx。
字符串将如下所示:
var splitMe = "[Key1,Value1][Key2,Value2][Key3,Value3][Key4,Value4]";
var splitedArray = Regex.Split(/'RegEx Here'/);
//Output value should like this one ["Key1,Value1","Key2,Value2","Key3,Value3","Key4,Value4"]
//this value also will be the key and value of a Dictionary<string,string>
答案 0 :(得分:1)
使用与Linq链接的Regex.Matches
来直接获取字典会更简单:
var input = "[Key1,Value1][Key2,Value2][Key3,Value3][Key4,Value4]";
var dictionary = Regex.Matches(input, @"\[(?<key>\w+),(?<value>\w+)\]")
.Cast<Match>()
.ToDictionary(x => x.Groups["key"].Value, x => x.Groups["value"].Value);
答案 1 :(得分:0)
这对你有用,我想:
\[(\w+,\w+)\]
我不确定您在密钥和值中可能包含哪些数据,但以下内容可能更具包容性?
\[([^,]+?,[^,]+?)\]
如果你想使用拆分仍然可以匹配你需要的东西:
(\[|\]\[|\])