C#关于正则匹配并提取txt文件中正负小数的问题
C#我想要提取如图文档里的正负小数存到数组里,代码怎么修改?privatevoidbutton2_Click(objectsender,EventArgse){strin...
C# 我想要提取如图文档里的正负小数存到数组里,代码怎么修改?private void button2_Click(object sender, EventArgs e) { string f; if (openFileDialog1.ShowDialog() == DialogResult.OK) { f = openFileDialog1.FileName; } string lineread=string.Empty ; string curFileName; curFileName = openFileDialog1.FileName; StreamReader sr = new StreamReader(curFileName); double[] wfwys = new double[12];//提取存到这个数组 int p = 0; while ((lineread = sr.ReadLine()) != null) { lineread = sr.ReadLine(); lineread = Convert.ToString(lineread); if ( ! Regex.IsMatch(lineread, @"[\u4e00-\u9fbb]"))//排除有汉字的行 { if (Regex.IsMatch(lineread, @"^[\\+\\-]?[\\d]+(\\.[\\d]+)?$"))//排除没有小数的行 { Match substring = Regex.Match(lineread, @"^[\\+\\-]?[\\d]+(\\.[\\d]+)?$"); wfwys[p] = double.Parse(substring.Value); p++; } } } textBox2.Text = Convert.ToString(wfwys[0]); textBox3.Text = Convert.ToString(wfwys[1]); textBox4.Text = Convert.ToString(wfwys[2]); 。。。。。。
展开
2个回答
展开全部
把用正则判断中文和小数的那一段程序改一下就行了.
你的C#程序我帮你改好了,你看看吧(改动的地方见注释,我测试过了,没问题)
private void button2_Click(object sender, EventArgs e) {
string f;
if (openFileDialog1.ShowDialog() == DialogResult.OK) {
f = openFileDialog1.FileName;
}
string lineread=string.Empty ;
string curFileName;
curFileName = openFileDialog1.FileName;
StreamReader sr = new StreamReader(curFileName);
double[] wfwys = new double[12];
int p = 0;
while ((lineread = sr.ReadLine()) != null) {
lineread = sr.ReadLine();
lineread = Convert.ToString(lineread);
MatchCollection mt=Regex.Matches(lineread, @"[\u4e00-\u9fa5]");//这里用Matches匹配,如果有一个汉字,则匹配成功.汉字的unicode编码是4e00到9fa5
if (mt.Count==0) { //如果没有汉字的行
MatchCollection mc=Regex.Matches(lineread, @"[+\-]?\d+\.\d+");//这里用Matches匹配,如果有小数,则匹配成功.因为小数不是一整行,所以去掉^和$
if (mc.Count>0) {//如果有小数的行
//Match substring = Regex.Match(lineread, @"[+-]?\d+\.\d+");//这里去掉这句,因为上面有匹配结果mc了
foreach (Match m in mc){ //这里遍历mc,因为一行只有一个小数,所以一行存一个小数到wfwys数组
wfwys[p] = double.Parse(m.Groups[0].Value); //这里把substring.Value改成m.Groups[0].Value
p++;
}
}
}
}
textBox2.Text = Convert.ToString(wfwys[0]);
textBox3.Text = Convert.ToString(wfwys[1]);
textBox4.Text = Convert.ToString(wfwys[2]);
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
代码如下:
private void button2_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
double[] wfwys = new double[12]; //提取存到这个数组
int p = 0;
string lineread = string.Empty;
while ((lineread = sr.ReadLine()) != null)
{
Match match = Regex.Match(lineread, @"^[A-Za-z]+=:(-?\d+\.\d+)$");
if (match.Groups.Count > 1)
{
wfwys[p++] = double.Parse(match.Groups[1].Value);
}
}
textBox2.Text = Convert.ToString(wfwys[0]);
textBox3.Text = Convert.ToString(wfwys[1]);
textBox4.Text = Convert.ToString(wfwys[2]);
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询