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]);
。。。。。。
参考网上的资源,最后编译成功了
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]);
textBox5.Text = Convert.ToString(wfwys[3]);
正则用起来真的好深奥啊......
double[] wfwys = {};
string pattern = @"(\-){0,1}\d+(\.\d+){0,1}";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
wfwys = File.ReadAllLines(openFileDialog1..FileName).Where(x => Regex.IsMatch(x, pattern))
.Select(x => Regex.Match(x, pattern).Value)
.Select(x => double.Parse(x))
.ToArray();
}