在正则表达式匹配上使用Convert.toint32()然后应用于numericupdown时发生c#FormatException

在正则表达式匹配上使用Convert.toint32()然后应用于numericupdown时发生c#FormatException,c#,regex,converter,numericupdown,formatexception,C#,Regex,Converter,Numericupdown,Formatexception,我会直截了当地说。我正在使用正则表达式从设置文件中获取匹配项。它只是获取默认值。我拿着火柴,让它打印字符串火柴。然后我使用Convert.toInt32(match)并将其转换为int tempval。这是代码 string[] settings = System.IO.File.ReadAllLines("Settings.txt"); MatchCollection settingsmatch; Regex expression = new Regex(@"first number: (\d

我会直截了当地说。我正在使用正则表达式从设置文件中获取匹配项。它只是获取默认值。我拿着火柴,让它打印字符串火柴。然后我使用Convert.toInt32(match)并将其转换为int tempval。这是代码

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行,但在运行时仍然得到错误


这是一个Formatexeption错误。我不明白。我认为我的匹配是一个字符串,所以Convert应该接受它。此外,messagebox.show正在向我显示一个数字。确切地说是35号。还有什么可能导致这种情况?

第一个匹配将是
第一个数字: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

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

// 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);

消息框到底显示了什么
35或
第一个号码:35
?如果将
“+”
Convert.ToInt32()
调用中保留,会发生什么情况?好像没有什么用。迈克尔:它在显示“35”。起初它显示的是“第一个数字:35”,但我修正了这个问题。Tieson:我一开始也没有使用“+”,因为FormatException的MSDN页面上说我可能缺少一个符号,所以我把它放进去了。我认为这可能会有帮助,但事实并非如此。我会把你的答案记下来。非常感谢。我有比赛,但我没有得到团体。我将更深入地研究小组。非常感谢你。