RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
C#正则表达式提取文本中以逗号间隔的数据

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

成都创新互联公司坚持“要么做到,要么别承诺”的工作理念,服务领域包括:网站建设、成都网站建设、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的西丰网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

   文本中内容格式

   1,2,3,4,5

   2,2,2,2,2

   3,3,3,3,3

   C#代码如下

public List> GetDataCSV(string path)
{
        string pattern = @"\d+";
	List> data = new List>();
	using(StreamReader sr = new StreamReader(@path, Encoding.GetEncoding("GB2312")))
	{
		string nextline;
		MatchCollection myMatches;
		while((nextline = sr.ReadLine()) != null )
		{
			myMatches = Regex.Matches(nextline, pattern);
			List rowdata = new List(); ;
			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> GetDataFromCSV(string path)
{
	List> data = new List>();
	using(StreamReader sr = new StreamReader(@path, Encoding.GetEncoding("GB2312")))
	{
		string nextline;
		while((nextline = sr.ReadLine()) != null )
		{
			List row = new List();
			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#正则表达式提取文本中以逗号间隔的数据
标题来源:http://cqwzjz.cn/article/ipdcos.html