繁体   English   中英

使用Regex从字符串中提取数字

[英]Number extraction from strings using Regex

我有这个C#代码,我找到了,然后根据我的需求进行了改进,但现在我想让它适用于所有数字数据类型。

    public static int[] intRemover (string input)
    {
        string[] inputArray = Regex.Split (input, @"\D+");
        int n = 0;
        foreach (string inputN in inputArray) {
            if (!string.IsNullOrEmpty (inputN)) {
                n++;
            }
        }
        int[] intarray = new int[n];
        n = 0;
        foreach (string inputN in inputArray) {
            if (!string.IsNullOrEmpty (inputN)) {
                intarray [n] = int.Parse (inputN);
                n++;
            }
        }
        return intarray;
    }

这适用于尝试从字符串中提取整数整数,但我遇到的问题是我正在使用的正则表达式不是设置为负数的数字或包含小数点的数字。 最后我的目标就像我说的那样,制定出一种适用于所有数值数据类型的方法。 有人可以帮帮我吗?

您可以match它而不是拆分它

public static decimal[] intRemover (string input)
{
    return Regex.Matches(input,@"[+-]?\d+(\.\d+)?")//this returns all the matches in input
                .Cast<Match>()//this casts from MatchCollection to IEnumerable<Match>
                .Select(x=>decimal.Parse(x.Value))//this parses each of the matched string to decimal
                .ToArray();//this converts IEnumerable<decimal> to an Array of decimal
}

[+-]? 匹配+- 0或1次

\\d+匹配1到多个数字

(\\.\\d+)? 匹配a(十进制后跟1到多位数)0到1次


以上代码的简化形式

    public static decimal[] intRemover (string input)
    {
        int n=0;
        MatchCollection matches=Regex.Matches(input,@"[+-]?\d+(\.\d+)?");
        decimal[] decimalarray = new decimal[matches.Count];

        foreach (Match m in matches) 
        {
                decimalarray[n] = decimal.Parse (m.Value);
                n++;
        }
        return decimalarray;
    }

尝试修改你这样的正则表达式:

 @"[+-]?\d+(?:\.\d*)?"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM