C# Regular Expression
In C#, a regular expression (or regex) is a pattern that specifies a set of strings. Regular expressions are used to validate input, search for patterns, and replace text in a string. In this tutorial, we'll discuss how to use regular expressions in C#.
Syntax
The syntax for defining a regular expression in C# is as follows:
Regex regex = new Regex(pattern);
The pattern parameter is the regular expression string that defines the pattern you want to match.
Example
Let's say we want to validate a phone number input in a C# program. We can use a regular expression to ensure that the phone number is in the correct format. Here's how we can implement it:
using System;
using System.Text.RegularExpressions;
class Program {
static void Main(string[] args) {
string phoneRegex = @"^\d{3}-\d{3}-\d{4}$";
Regex regex = new Regex(phoneRegex);
Console.WriteLine("Enter phone number (XXX-XXX-XXXX):");
string input = Console.ReadLine();
if (regex.IsMatch(input)) {
Console.WriteLine("Valid phone number");
} else {
Console.WriteLine("Invalid phone number");
}
}
}
Now, we can enter a phone number and the program will validate it using the regular expression pattern.
Output
When we run the example code above and enter a valid phone number (e.g. 123-456-7890), the output will be:
Valid phone number
If we enter an invalid phone number (e.g. 1234567890), the output will be:
Invalid phone number
Explanation
In the example above, we defined a regular expression pattern that matches phone numbers in the format XXX-XXX-XXXX. We then created a Regex object using the pattern and used it to validate user input in a C# console application.
Use
Regular expressions can be used in a variety of ways in C#, such as to validate input, search for patterns, and replace text in a string. They are useful for tasks such as form validation, data filtering, and text processing.
Important Points
- Regular expressions are case-sensitive by default, but you can use the RegexOptions.IgnoreCase option to make them case-insensitive.
- The ^ and $ characters in a regular expression denote the beginning and end of a string, respectively.
- The \d character in a regular expression matches any digit, and the {n} syntax matches n instances of the preceding expression.
Summary
In this tutorial, we discussed how to use regular expressions in C# to validate phone numbers. We covered the syntax, example, output, explanation, use, and important points of regular expressions in C#. With this knowledge, you can now use regular expressions in your C# code to validate input, search for patterns, and replace text in a string.