繁体   English   中英

从字符串正则表达式中获取数字

[英]get number from string regex

我想得到 C# 字符串上的所有数字

例如:

sadsad 2 fsdg 4 njnjk 5 njnsdf 9 jytjtj

我想得到

这些数字,我该怎么做? 谢谢

string text = "sadsad 2 fsdg 4 njnjk 5 njnsdf 9 jytjtj 123 456 78 9";
            Regex regex = new Regex(@"\d{1,5}" /* up to 5 digits */, RegexOptions.Compiled);

            List<int> numberList = regex.Matches(text).Cast<Match>().Select(m => int.Parse(m.Value)).ToList();

正则表达式记录在此处: https : //msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex(v= vs.110).aspx

为了测试正则表达式,这个网站对我很有帮助: http : //regexr.com/

假设您想要一个包含 Int32 值的列表,它可能如下所示。

        string pattern = "[0-9]";
        string input = "sadsad 2 fsdg 4 njnjk 5 njnsdf 9 jytjtj";
        Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
        MatchCollection result = rgx.Matches(input);

        var resultList = new List<Int32>(); 
        foreach (Match match in result)
        {
            resultList.Add(Int32.Parse(match.Value));
        }

暂无
暂无

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

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