only numbers in csharp

To extract only numbers from a string in C#, you can use regular expressions. Here's an example code snippet that demonstrates how to do this:

main.cs
using System.Text.RegularExpressions;

string input = "abc123xyz456";
string pattern = @"\d+";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
    Console.WriteLine(match.Value);
}
225 chars
10 lines

In this example, the input string "abc123xyz456" contains both letters and numbers. The regular expression pattern @"\d+" matches one or more digits (0-9). The Regex.Matches method is used to find all matches of the pattern in the input string.

The output of this code would be:

main.cs
123
456
8 chars
3 lines

You can then use this extracted string of numbers for further processing or conversion to a desired data type using the appropriate type conversion method.

gistlibby LogSnag