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.

Download  Run Code

 
The above program throws IndexOutOfRangeException if the string is empty or null. You can handle this as follows:

Download  Run Code

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 |.

Download  Run Code

 
You may use Verbatim string literals (@) to escape special characters like backslash characters.

Download  Run Code

That’s all about checking if a string starts with a number in C#.