如何摆脱“输入字符串格式不正确”?错误? [英] How do I get rid of "input string was not in a correct format" error?

查看:106
本文介绍了如何摆脱“输入字符串格式不正确”?错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



我有以下代码:



 int tSectionNo = Convert.ToInt32(Regex.Match(TempSectionTitleArray [icm],(。+)\\ |)。Groups [1] .Value); 





我收到以下错误:



输入字符串的格式不正确





 TempSectionTitleArray 

是一个默认情况下初始化为null的String数组。



请帮忙。



问候

Aman Chaurasia



我尝试过:



 int tSectionNo = Convert.ToInt32(正则表达式.Match(TempSectionTitleArray [icm],(。+)\\ |)。Groups [1] .Value); 

解决方案

不要在一个语句中完成所有操作。使用各自的语句分配给变量并检查有效性。



您的代码可能出现的错误来源是没有匹配或匹配可以'转换为整数。



另一个提示:为了使正则表达式更易读,请使用 @ 语法避免多次转义:

  @ (。+) \ | 



您应该使用类似(未经测试的):

  int  tSectionNo =  0 ; 
匹配匹配= Regex.Match(TempSectionTitleArray [icm], @ (。+)\ | );
if (match.Success)
{
// < span class =code-comment>分配给变量以便可以检查和/或

// 已添加到错误消息中
string sub = match.Groups [ 1 ]值。
if (!Int32.TryParse(sub, out tSectionNo))
{
// 不是整数
}
}
else
{
// 不匹配
}





当输入字符串包含多个时,还有另一个可能的错误源 | 字符。然后正则表达式将匹配最后一个 | 之前的所有文本(贪婪匹配),以便转换为 int 失败。为了避免指定非贪婪(懒惰)匹配:

  @  \(+。?)| 

[/编辑]


Hello,

I have the following line of code:

int tSectionNo = Convert.ToInt32(Regex.Match(TempSectionTitleArray[icm], "(.+)\\|").Groups[1].Value);



and I am getting the following error:

Input string was not in a correct format



TempSectionTitleArray

is a String array initialized to null by default.

Please help.

Regards
Aman Chaurasia

What I have tried:

int tSectionNo = Convert.ToInt32(Regex.Match(TempSectionTitleArray[icm], "(.+)\\|").Groups[1].Value);

解决方案

Don't do it all in one statement. Use the statements each on it's own line assigning to a variable and checking for validity.

Possible error sources with your code are that there is no match or the match can't be converted to an integer.

Another tip: To make the regex better readable use the @ syntax to avoid multiple escaping:

@"(.+)\|"


You should use something like (untested):

int tSectionNo = 0;
Match match = Regex.Match(TempSectionTitleArray[icm], @"(.+)\|");
if (match.Success)
{
    // Assign to a variable so that it can be inspected and/or 
    //  added to an error message
    string sub = match.Groups[1].Value;
    if (!Int32.TryParse(sub, out tSectionNo))
    {
        // Not an integer
    }
}
else
{
    // No match
}


[EDIT]
There is another probable error source when the input string contains multiple | characters. Then the regex would match all the text before the last | (greedy matching) so that converting to int fails. To avoid that specify non-greedy (lazy) matching:

@"(.+?)\|"

[/EDIT]


这篇关于如何摆脱“输入字符串格式不正确”?错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆