使用正則表達式提取文本數據到內存是很方便的技術,下面通過一個例子介紹一下如何使用正則表達式提取文本
文本中內容格式
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; }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。