c# FormatException当使用Convert.toint32()对regex匹配,然后应用到numericu

本文关键字:匹配 regex 然后 应用 numericu FormatException Convert toint32 | 更新日期: 2023-09-27 18:18:24

我开门见山了。我使用正则表达式从设置文件中获得匹配。它只是获取默认值。我取match,让它打印String match。然后我使用Convert.toInt32(match)并将其放入int临时变量中。代码如下:
string[] settings = System.IO.File.ReadAllLines("Settings.txt");
MatchCollection settingsmatch;
Regex expression = new Regex(@"first number: ('d+)");
settingsmatch = expression.Matches(settings[0]);
MessageBox.Show(settingsmatch[0].Value);
int tempval = Convert.ToInt32("+" + settingsmatch[0].Value.Trim());   //here is the runtime error
numericUpDown1.Value = tempval;

这里是设置文本文件:

first number: 35
second number: 4
default test file: DefaultTest.txt

我知道问题是转换,因为我注释掉了numericupdown行,仍然在运行时得到错误。

这是一个formatexception错误。我不明白。我认为我的匹配是一个字符串,所以转换应该采取它。此外还有消息框。Show是给我看一个数字。确切地说,是35。还有什么原因会导致这种情况?

c# FormatException当使用Convert.toint32()对regex匹配,然后应用到numericu

第一个匹配将是first number: 35。为了得到匹配的数字,使用Match.Groups属性。

settingsmatch = expression.Matches(settings[0]);
MessageBox.Show(settingsmatch[0].Groups[1].Value);
int tempval = Convert.ToInt32(settingsmatch[0].Groups[1].Value); // .Trim() is not needed because you are matching digits only

您正在做的是将整个匹配值转换为Integer。您需要转换第一个组捕获的值。

// convert the value of first group instead of entire match
//    settingsmatch[0].Value is "first number: 35"
//    settingsmatch[0].Groups[1].Value is "35"
int tempval = Convert.ToInt32("+" + settingsmatch[0].Groups[1].Value);