C# regular expressions
Regular expressions (regex) in C# provide a powerful and efficient way to search, replace, and validate strings. Regular expressions consist of a pattern, which is a sequence of characters that define a search pattern.
C# provides a dedicated namespace System.Text.RegularExpressions
for working with regular expressions. The Regex
class is used to create a regular expression object, which can then be used to match patterns against input strings.
Here is an example of using regular expressions in C# to match a pattern in a string:
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "The quick brown fox jumps over the lazy dog."; // Define a regular expression pattern string pattern = @"\b\w{5}\b"; // Create a regular expression object Regex regex = new Regex(pattern); // Find all matches MatchCollection matches = regex.Matches(input); // Print each match foreach (Match match in matches) { Console.WriteLine(match.Value); } } }
In this example, the regular expression pattern \b\w{5}\b
matches any word in the input string that is exactly 5 characters long. The \b
character is a word boundary, and \w
represents any word character (letters, digits, and underscores).
The Regex
class provides many other methods for working with regular expressions, such as Match
, Replace
, Split
, and more. Regular expressions can be complex, but with practice, they can be a powerful tool for string manipulation in C#.