Home  >  Article  >  Backend Development  >  How to detect which numbers are in a string in C#?

How to detect which numbers are in a string in C#?

黄舟
黄舟Original
2017-02-20 11:19:241447browse

C# How to detect which numbers are in a string?

  //测试函数
        private void Form1_Load(object sender, EventArgs e)
        {
            foreach (var number in ExtractNumbersFromString("abc2345 345fdf678 jdhfg945"))
            {
                MessageBox.Show(number.ToString());
            }
        }

        private IEnumerable<int> ExtractNumbersFromString(string s)
        {
            //Regex.Matches 方法:在输入字符串中搜索正则表达式的所有匹配项并返回所有匹配。
            //一次或多次匹配前面的字符或子表达式。等效于 {1,}。如果将+去掉,就是
            //return Regex.Matches(s, @"\d+").Cast<Match>().Select(m => Convert.ToInt32(m.Value));
            return Regex.Matches(s, @"\d").Cast<Match>().Select(m => Convert.ToInt32(m.Value));
        }

"abc2345 345fdf678 jdhfg945"
When testing the above example, if there is a plus sign, it will be output like this:

2345  
345
678
945

When there is no +, it will be output like this :

2
3
4
5
3
.......

The above is C#. How to detect which numbers are in a string string? For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn