溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C#正則表達式提取文本中以逗號間隔的數據

發布時間:2020-06-17 22:24:36 來源:網絡 閱讀:2277 作者:nifu2010 欄目:編程語言

   使用正則表達式提取文本數據到內存是很方便的技術,下面通過一個例子介紹一下如何使用正則表達式提取文本

   文本中內容格式

   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;
}


向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女