从与非位数之间的字符串解析数 [英] Parse a number from a string with non-digits in between

查看:66
本文介绍了从与非位数之间的字符串解析数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作.NET项目,我试图来解析从string的数值。例如,

 字符串s =12ACD; 
INT T = someparefun(S);
打印(T)// T应当是12



一对夫妇的假设是




  1. 的字符串模式总是将是字符数如下。

  2. 数字部分将永远是一个或两位数字的值。



有没有C#预定义的功能来分析,从字符串?


的数值< DIV CLASS =h2_lin>解决方案

有没有这样的功能,至少没有我所知道的。但是,一种方法是使用正则表达式来去除一切不是一个数字:

 使用系统;使用System.Text.RegularExpressions 
;

INT结果=
//转换(系统)类进来非常方便,每次
//你要转换的东西。
Convert.ToInt32(
Regex.Replace(
12ACD,//我们输入
[^ 0-9],//选择一切,是不是在0-9
,范围//替换为空字符串
))。

本功能将产生 12 12ABC ,所以如果你需要能够处理负数,你需要一个不同的解决方案。它也并不安全,如果你传递唯一的非数字就会产生一个 FormatException 。下面是一些示例数据:

 12ACD=> 12 
12a5上,从而=> 125
CA12a中=> 12
-12AD=> 12
,=> FormatException
AAAA=> FormatException

一个有点冗长,但更安全的方法是使用的 int.TryParse()

 使用系统; 
使用System.Text.RegularExpression;

公共静态INT ConvertToInt(字符串输入)
{
//替换一切,没有一个数字。
字符串inputCleaned = Regex.Replace(输入[^ 0-9],);

int值= 0;

//试图解析INT,失败时返回假的。
如果(int.TryParse(inputCleaned,超时值))
{
//从分析的结果可以安全返回。
返回值;
}

返回0; //或任何其他默认值。
}



一些示例数据再次:

 12ACD=> 12 
12a5上,从而=> 125
CA12a中=> 12
-12AD=> 12
,=> 0
AAAA=> 0



或者,如果你只想要的第一个的字符串中的数字,基本上在会议未尝不是一个数字停止,我们突然也可以把负数轻松:

 使用系统; 
使用System.Text.RegularExpression;

公共静态INT ConvertToInt(字符串输入)
{
//带或不带前导负匹配的第一个numebr。
匹配匹配= Regex.Match(? - [0-9] +输入);

如果(match.Success)
{
//没有必要在这里的TryParse,比赛必须至少为
// 1位数。
返回int.Parse(match.Value);
}

返回0; //或任何其他默认值。
}



我们再一次测试:

 12ACD=> 12 
12a5上,从而=> 12
CA12a中=> 12
-12AD=> -12
,=> 0
AAAA=> 0



总之,如果我们谈论的是用户输入的,我会考虑不接受无效的输入可言,只有使用 int.TryParse()没有一些额外的魔术和失败告知输入是次优的用户(也许有效数字再次提示)。


I am working on .NET project and I am trying to parse only the numeric value from string. For example,

string s = "12ACD";
int t = someparefun(s); 
print(t) //t should be 12

A couple assumptions are

  1. The string pattern always will be number follow by characters.
  2. The number portion always will be either one or two digits value.

Is there any C# predefined function to parse the numeric value from string?

解决方案

There's no such function, at least none I know of. But one method would be to use a regular expression to remove everything that is not a number:

using System;
using System.Text.RegularExpressions;

int result =
    // The Convert (System) class comes in pretty handy every time
    // you want to convert something.
    Convert.ToInt32(
        Regex.Replace(
            "12ACD",  // Our input
            "[^0-9]", // Select everything that is not in the range of 0-9
            ""        // Replace that with an empty string.
    ));

This function will yield 12 for 12ABC, so if you need to be able to process negative numbers, you'll need a different solution. It is also not safe, if you pass it only non-digits it will yield a FormatException. Here is some example data:

"12ACD"  =>  12
"12A5"   =>  125
"CA12A"  =>  12
"-12AD"  =>  12
""       =>  FormatException
"AAAA"   =>  FormatException

A little bit more verbose but safer approach would be to use int.TryParse():

using System;
using System.Text.RegularExpression;

public static int ConvertToInt(String input)
{
    // Replace everything that is no a digit.
    String inputCleaned = Regex.Replace(input, "[^0-9]", "");

    int value = 0;

    // Tries to parse the int, returns false on failure.
    if (int.TryParse(inputCleaned, out value))
    {
        // The result from parsing can be safely returned.
        return value;
    }

    return 0; // Or any other default value.
}

Some example data again:

"12ACD"  =>  12
"12A5"   =>  125
"CA12A"  =>  12
"-12AD"  =>  12
""       =>  0
"AAAA"   =>  0

Or if you only want the first number in the string, basically stopping at meeting something that is not a digit, we suddenly also can treat negative numbers with ease:

using System;
using System.Text.RegularExpression;

public static int ConvertToInt(String input)
{
    // Matches the first numebr with or without leading minus.
    Match match = Regex.Match(input, "-?[0-9]+");

    if (match.Success)
    {
        // No need to TryParse here, the match has to be at least
        // a 1-digit number.
        return int.Parse(match.Value);
    }

    return 0; // Or any other default value.
}

And again we test it:

"12ACD"  =>  12
"12A5"   =>  12
"CA12A"  =>  12
"-12AD"  =>  -12
""       =>  0
"AAAA"   =>  0

Overall, if we're talking about user input I would consider not accepting invalid input at all, only using int.TryParse() without some additional magic and on failure informing the user that the input was suboptimal (and maybe prompting again for a valid number).

这篇关于从与非位数之间的字符串解析数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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