C#正则表达式提取文本中以逗号间隔的数据
生活随笔
收集整理的這篇文章主要介紹了
C#正则表达式提取文本中以逗号间隔的数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ?使用正則表達式提取文本數據到內存是很方便的技術,下面通過一個例子介紹一下如何使用正則表達式提取文本
? ?文本中內容格式
? ?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; }轉載于:https://blog.51cto.com/11697581/1825633
總結
以上是生活随笔為你收集整理的C#正则表达式提取文本中以逗号间隔的数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第10章 嵌入式linux的调试技术
- 下一篇: Android App截包工具