How to Extract Numbers from String in C# Easily
In C#, you can extract numbers from a string using
Regex to find digit patterns or by iterating through characters and checking if they are digits with char.IsDigit(). The Regex.Matches() method is a common and efficient way to get all numbers as strings from any text.Syntax
Use Regex.Matches(input, pattern) to find all matches of a pattern in a string. The pattern \d+ matches one or more digits in a row.
input: The string to search.pattern: The regular expression pattern to find numbers.Matches: Returns a collection of matches found.
csharp
using System.Text.RegularExpressions; var input = "abc123def456"; var matches = Regex.Matches(input, "\d+"); foreach (Match match in matches) { Console.WriteLine(match.Value); }
Output
123
456
Example
This example shows how to extract all numbers from a string using Regex and print them one by one.
csharp
using System; using System.Text.RegularExpressions; class Program { static void Main() { string text = "Order 123 shipped on 2023-06-15."; var numbers = Regex.Matches(text, "\d+"); Console.WriteLine("Numbers found in the string:"); foreach (Match number in numbers) { Console.WriteLine(number.Value); } } }
Output
123
2023
06
15
Common Pitfalls
One common mistake is trying to convert the entire string to a number directly, which fails if the string contains letters or symbols. Another is forgetting that Regex.Matches returns matches as strings, so you need to parse them to numbers if needed.
Also, using char.IsDigit() alone extracts digits one by one, not full numbers, so you might get separate digits instead of whole numbers.
csharp
using System; using System.Text.RegularExpressions; class Program { static void Main() { string text = "abc123def"; // Wrong: trying to parse whole string // int number = int.Parse(text); // Throws exception // Right: extract numbers first var matches = Regex.Matches(text, "\d+"); foreach (Match m in matches) { int num = int.Parse(m.Value); Console.WriteLine(num); } } }
Output
123
Quick Reference
- Regex pattern:
\d+matches one or more digits. - Regex.Matches: Finds all matches in a string.
- char.IsDigit: Checks if a character is a digit.
- Parsing: Use
int.Parse()orint.TryParse()to convert string numbers to integers.
Key Takeaways
Use Regex with pattern \d+ to extract all number sequences from a string in C#.
Regex.Matches returns matches as strings; parse them to integers if needed.
Avoid parsing the whole string directly if it contains non-digit characters.
char.IsDigit checks single characters but does not extract full numbers.
Use int.TryParse for safe conversion from string to number.