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

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

黄舟
Release: 2017-02-20 11:19:24
Original
1475 people have browsed it

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));
        }
Copy after login

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

2345  
345
678
945
Copy after login

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

2
3
4
5
3
.......
Copy after login

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 (m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template