Float.Parse 0 value
本文关键字:value Parse Float | 更新日期: 2023-09-27 18:34:11
>结果:
00
00
-6361 0
-6384 -6672
00
0 -6793...
法典:
string regex = @"X:(.*?)'sY:(.*?)";
if (File.Exists("minelist.log"))
File.Delete("minelist.log");
File.Copy(war3path + "''minelist.log", "minelist.log");
string[] crdlist = File.ReadAllLines("minelist.log");
for (int i = 0; i < crdlist.Length;i++)
{
Match COORM = Regex.Match(crdlist[i], regex);
if (COORM.Success)
{
float x = 0.0f, y = 0.0f;
float.TryParse(COORM.Groups[1].Value, out x);
float.TryParse(COORM.Groups[2].Value, out y);
MessageBox.Show(x.ToString(), y.ToString());
}
}
if (File.Exists("minelist.log"))
File.Delete("minelist.log");
因此,仅解析某些值。其他 = 0。
文件
结果:0 00 06361 0-6384 66720 00 -6793...
您的正则表达式与您认为匹配的内容不匹配。可以使用MessageBox
(或通过在调试器中单步跳过)检查捕获组。问题是你用.*?
来捕获数字组:任何字符的任意数量,懒惰;然后在foreach
循环中,您使用了TryParse()
但没有检查结果!在结果你得到"0"的行上,正则表达式可能停止得太快了。TryParse()
将失败,并将X
和Y
保留为默认值。
正确解析所有内容的完整控制台示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Globalization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] crdlist = {
"X:-6625.5 Y:-6585.5",
"X:-6601.25 Y:-6703.75",
"X:-6361 Y:-6516.5",
"X:-6384 Y:-6672",
"X:-6400.25 Y:-6847.75",
"X:-6608.75 Y:-6793",
"X:-6739.75 Y:-6872",
"X:-6429.25 Y:-6940",
"X:-7015.5 Y:-6835.5",
"X:-7117 Y:-6903",
"X:-6885.5 Y:-6662.5",
"X:-6861.5 Y:-6597",
"X:-7006.5 Y:-6728",
"X:-7009 Y:-6608.75",
"X:-6924 Y:-6798",
"X:-6970.25 Y:-6898.25",
"X:-6495.25 Y:-6775",
"X:-7112.5 Y:-6614.5",
"X:-7115.25 Y:-6717.25",
"X:-7113.25 Y:-6835.5",
"X:-6493 Y:-6620.25"
};
Regex re = new Regex(@"^' *X':(['-'.0-9]*)' *Y':(['-'.0-9]*)' *$", RegexOptions.Compiled);
var us_EN = new CultureInfo("en-US");
foreach(var line in crdlist)
{
Match m = re.Match(line);
if (m.Success)
{
String X = m.Groups[1].Value;
String Y = m.Groups[2].Value;
float fX = float.Parse(X, us_EN);
float fY = float.Parse(Y, us_EN);
Console.WriteLine("X={0}, Y={1}", fX, fY);
}
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
使用以下正则表达式模式:
string regex = @"X:(-*d*.*d*)'sY:(-*d*.*d*)";