get the number of numbers in a string in csharp

One approach to achieve this is by using Regular Expressions (Regex) in C#.

Here's an example code snippet that uses Regex to find all the numbers in a string and returns the total count:

main.cs
using System.Text.RegularExpressions;

string input = "abc123def456ghi";
int count = Regex.Matches(input, @"\d+").Count;

Console.WriteLine(count); // Output: 2
161 chars
7 lines

Explanation:

  • \d matches any digit (0-9).
  • + means to match one or more occurrences of the previous item, which is \d in this case.
  • Regex.Matches() returns a collection of all matches found in the input string.
  • .Count returns the total count of matches found.

In the example above, the code counts two numbers in the input string abc123def456ghi.

gistlibby LogSnag