正则表达式的相关文章可以参考
这里主要记录用正则表达式从字符串中解析出三维数组的方法。
用到的字符:
[a-z] 匹配指定范围内的任意字符。例如,‘[a-z]'可以匹配'a'到'z'范围内的任意小写字母字符
\d 匹配一个数字字符,等价于[0-9]
+ 匹配前面的一次或多次的子表达式
* 匹配前面的零次或多次的子表达式
@表示避免转义字符,\就是\,否则一个\和后面的字符结合为转义字符,需要两个\\才能表示一个\
由于在正则表达式中“ \ ”、“ ? ”、“ * ”、“ ^ ”、“ $ ”、“ + ”、“(”、“)”、“ | ”、“ { ”、“ [ ”等字符已经具有一定特殊意义,如果需要用它们的原始意义,则应该对它进行转义,
例如希 望在字符串中至少有一个“ \ ”,那么正则表达式应该这么写: \\+
如对于[]是表示中括号,如果想获取中括号的单个字符,如[,则要这么写\\[
一、解析一维数组
/// <summary>
/// [29,20,2,0]
/// </summary>
public static List<int> stringToListIntNew(string value)
{
List<int> list = new List<int>();
if (!string.IsNullOrEmpty(value))
{
//Regex reg = new Regex("\\d+"); // 每次匹配一个或多个数字
Regex reg = new Regex(@"\d+");
var match = reg.Match(value);
while (match != Match.Empty)
{
list.Add(int.Parse(match.Value));
match = match.NextMatch();
}
}
return list;
}
\d 匹配一个数字
\d+ 匹配一个或多个数字
二、解析二维数组
/// <summary>
/// [[630000,1,0,0],[630000,1,0,0]]
/// </summary>
public static List<List<int>> stringToListsIntNew(string value)
{
List<List<int>> lists = new List<List<int>>();
List<int> list = new List<int>();
if (!string.IsNullOrEmpty(value))
{
//Regex r = new Regex("\\[(\\d+,?)+\\]"); // 拆一维[630000,1,0,0]
Regex r = new Regex(@"\[(\d+,?)+\]");
Match match = r.Match(value);
while (match != Match.Empty)
{
list = stringToListIntNew(match.Value);
lists.Add(list);
match = match.NextMatch();
}
}
return lists;
}
\d+,? 匹配多个数字 和 , 即:630000,
(\d+,?)+ 表达式(多个数字,)的多次匹配 即:630000,1,0,0
\[ 匹配[
三、解析三维数组
/// <summary>
/// [[[820002,5,1,0],[820000,5,1,0]],[[620010,4,1,0],[210089,1,1,0],[820002,15,1,0]]]
/// </summary>
public static List<List<List<int>>> stringToListssInt(string value)
{
List<List<List<int>>> listss = new List<List<List<int>>>();
List<List<int>> lists = new List<List<int>>();
if (!string.IsNullOrEmpty(value))
{
//Regex r = new Regex("\\[(\\[(\\d+,?)+\\],?)+\\]"); // 先拆二维[[820002,5,1,0],[820000,5,1,0]]
//Regex r = new Regex(@"\[(\[(\d+,?)+\],?)+\]");
Regex r = new Regex(@"\[(\[(\d+,?)+\],?)*\]"); // + 改为 * 空的数组 [] 也可以匹配
Match match = r.Match(value);
while (match != Match.Empty)
{
lists = stringToListsIntNew(match.Value);
listss.Add(lists);
match = match.NextMatch();
}
}
return listss;
}
拆二维数组的另一种方法:
/// <summary>
/// [[630000,1,0,0],[630000,1,0,0]]
/// </summary>
public static List<List<int>> stringToListsInt(string value)
{
List<List<int>> lists = new List<List<int>>();
if (!string.IsNullOrEmpty(value))
{
Regex r = new Regex(@"\[(?:(\d+),?)+\]"); // 拆一维[630000,1,0,0]
Match match = r.Match(value);
while (match != Match.Empty)
{
var capture = match.Groups[1].Captures;
if (capture.Count > 0)
{
List<int> tmp = new List<int>();
for (int i = 0; i < capture.Count; i++)
{
tmp.Add(int.Parse(capture[i].Value));
}
lists.Add(tmp);
match = match.NextMatch();
}
}
}
return lists;
}