使用正则表达式提取文本数据到内存是很方便的技术,下面通过一个例子介绍一下如何使用正则表达式提取文本
文本中内容格式
1,2,3,4,5
2,2,2,2,2
3,3,3,3,3
C#代码如下
public List<List<string>> GetDataCSV(string path)
{
string pattern = @"\d+";
List<List<string>> data = new List<List<string>>();
using(StreamReader sr = new StreamReader(@path, Encoding.GetEncoding("GB2312")))
{
string nextline;
MatchCollection myMatches;
while((nextline = sr.ReadLine()) != null )
{
myMatches = Regex.Matches(nextline, pattern);
List<string> rowdata = new List<string>(); ;
foreach(Match nextmatch in myMatches)
{
rowdata.Add(nextmatch.Value);
}
data.Add(rowdata);
}
//消除最后的空行
for(int i=data.Count-1;i>=0;i--)
{
if(data[i].Count ==0)
{
data.Remove(data[i]);
}
else
{
break;
}
}
}
return data;
}
上面代码试用标准格式,逗号间都有数据,此外逗号间无数据如
1,2,3,4
2,,3,3
3,3,3,3
方法如下:
public List<List<string>> GetDataFromCSV(string path)
{
List<List<string>> data = new List<List<string>>();
using(StreamReader sr = new StreamReader(@path, Encoding.GetEncoding("GB2312")))
{
string nextline;
while((nextline = sr.ReadLine()) != null )
{
List<string> row = new List<string>();
char[] charArray = nextline.ToCharArray();
int flag = 0;
for (int i = 0; i < charArray.Length;i++)
{
if(charArray[i] != ',' && i != (charArray.Length -1))
{
continue;
}
else
{
if(flag == i)
{
row.Add("-1");//若空值赋值-1,此处赋值可自行定义
flag = i + 1;
if(i == charArray.Length - 1)//若最后一个为逗号,需在加一个空值,即添加-1代表空
{
row.Add("-1");
}
}
else
{
string s;
if(i == charArray.Length - 1)//最后一个数时提取字符串length=i-flag + 1
{
s = nextline.Substring(flag, i - flag + 1);
}
else
{
s = nextline.Substring(flag, i - flag);
}
flag = i + 1;
row.Add(s);
}
}
}
data.Add(row);
}
//消除最后的空行
for(int i=data.Count-1;i>=0;i--)
{
if(data[i].Count ==0)
{
data.Remove(data[i]);
}
else
{
break;
}
}
}
return data;
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。