C#正则表达式提取文本中以逗号间隔的数据
2016-07-12 10:15
645 查看
使用正则表达式提取文本数据到内存是很方便的技术,下面通过一个例子介绍一下如何使用正则表达式提取文本
文本中内容格式
1,2,3,4,5
2,2,2,2,2
3,3,3,3,3
C#代码如下
1,2,3,4
2,,3,3
3,3,3,3
方法如下:
文本中内容格式
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; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- C位出道后却遇前狼后虎,生鲜电商多点如何突围?
- 如何成为一名黑客
- IE:如何做到全屏显示
- 如何解决双网卡冲突
- 如何利用“IP地址欺骗”
- 如何选择路由协议
- 不限连接数如何设置?
- 如何隐藏程序的运行
- 如何追踪入侵者
- 如何进行系统配置
- 如何高效的使用内存
- 如何设置域名接口
- Lua学习笔记之运算符和表达式
- Lua教程(三):表达式和语句
- Lua基础教程之赋值语句、表达式、流程控制、函数学习笔记
- mysql 中存在null和空时创建唯一索引的方法
- Ruby中case表达式详解
- C#中string.Empty和null的区别详解
- 基于不要返回null之EmptyFactory的应用详解