使用正则表达式提取文本数据到内存是很方便的技术,下面通过一个例子介绍一下如何使用正则表达式提取文本

   文本中内容格式

   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.C