C#关于正则匹配并提取txt文件中正负小数的问题

2025-04-14 08:20:31
推荐回答(2个)
回答1:

把用正则判断中文和小数的那一段程序改一下就行了.

你的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, @"[一-龥]");//这里用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]);

回答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]);
}
}
}