Check if a string starts with a number in C#
This article illustrates the different techniques to check if a string starts with a number in C#.
1. Using Char.IsDigit() method
A simple solution to check if a string starts with a number is to extract the first character in the string and check for the number with the char.IsDigit() method. The following code example demonstrates how to use the IsDigit() method to check if a string starts with a number.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string input = "1@One"; bool startWithNum = char.IsDigit(input[0]); Console.WriteLine(startWithNum); // True } } |
The above program throws IndexOutOfRangeException if the string is empty or null. You can handle this as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string input = "1@One"; bool startWithNum = !string.IsNullOrEmpty(input) && char.IsDigit(input[0]); Console.WriteLine(startWithNum); // True } } |
2. Using Regex.IsMatch() method
Another option is to use regular expressions to determine whether a string starts with a number. This can be done using the Regex.IsMatch() method, which returns true if the string matches the given regular expression. The following code example demonstrates its usage. Here, ^ matches with the start of the string, and (google|microsoft|youtube) matches the string from the beginning with any of the values separated by |.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Text.RegularExpressions; public class Example { public static void Main() { string input = "1@One"; bool startWithNum = Regex.IsMatch(input, "^\\d"); Console.WriteLine(startWithNum); // True } } |
You may use Verbatim string literals (@) to escape special characters like backslash characters.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Text.RegularExpressions; public class Example { public static void Main() { string input = "1@One"; bool startWithNum = Regex.IsMatch(input, @"^\d"); Console.WriteLine(startWithNum); // True } } |
That’s all about checking if a string starts with a number in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)