Regular Expressions in C# with Examples: From Theory to Practice
\n\nRegular expressions (regex) are a powerful tool for searching, extracting, and replacing text based on patterns. In C# (.NET), working with regex is implemented through the System.Text.RegularExpressions namespace and the Regex class. In this article, we will cover the main features with real examples: from simple search to email and phone validation.
1. Basics: The Regex Class and Its Methods
\n\nThe main class for working with regex is Regex. It provides static and instance methods. Here are the main ones:
- \n
IsMatch— checks if the string contains a match for the pattern. \nMatch— finds the first match. \nMatches— finds all matches. \nReplace— replaces matches with a specified string. \nSplit— splits the string based on a pattern. \n
Example 1. Simple Check
\nusing System;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n static void Main()\n {\n string text = "Hello, my number: 123-456-7890";\n string pattern = @"\\d{3}-\\d{3}-\\d{4}";\n\n if (Regex.IsMatch(text, pattern))\n {\n Console.WriteLine("Number found!");\n }\n }\n}\n\n\nIn this example, \\d{3} means "exactly three digits". The backslash is escaped using @ (verbatim string).
2. Capture Groups and Data Extraction
\n\nCapture groups allow you to extract parts of a match. They are defined with parentheses (). Each group gets a sequential number (starting from 1).
Example 2. Extracting Username and Domain from an Email
\nstring email = "user@example.com";\nstring pattern = @"^(\\w+)@(\\w+\\.\\w+)$";\n\nMatch match = Regex.Match(email, pattern);\n\nif (match.Success)\n{\n Console.WriteLine($"Username: {match.Groups[1].Value}"); // user\n Console.WriteLine($"Domain: {match.Groups[2].Value}"); // example.com\n}\n\n\nHere, (\\w+) captures one or more alphanumeric characters. ^ and $ are anchors for the start and end of the string.
Example 3. Parsing a URL
\nstring url = "https://pythonlib.ru/page?id=42";\nstring pattern = @"^(https?)://([^/]+)(/.*)?$";\n\nMatch m = Regex.Match(url, pattern);\nif (m.Success)\n{\n Console.WriteLine($"Protocol: {m.Groups[1].Value}"); // https\n Console.WriteLine($"Domain: {m.Groups[2].Value}"); // pythonlib.ru\n Console.WriteLine($"Path: {m.Groups[3].Value}"); // /page?id=42\n}\n\n\n3. Text Replacement and Removal
\n\nThe Replace method allows you to replace found fragments. You can use backreferences like $1, $2 to insert groups.
Example 4. Formatting a Phone Number
\nstring raw = "89161234567";\nstring pattern = @"(\\d{1})(\\d{3})(\\d{3})(\\d{2})(\\d{2})";\nstring replacement = "+7 ($2) $3-$4-$5";\n\nstring formatted = Regex.Replace(raw, pattern, replacement);\nConsole.WriteLine(formatted); // +7 (916) 123-45-67\n\n\nExample 5. Removing Extra Spaces
\nstring text = "This text has extra spaces.";\nstring cleaned = Regex.Replace(text, @"\\s+", " ");\nConsole.WriteLine(cleaned); // "This text has extra spaces."\n\n\n\\s+ — one or more whitespace characters. We replace them with a single space.
4. Real-World Cases: Email and Phone Validation
\n\nIn practice, regex is most often used for validating user input. Here are two typical examples.
\n\nEmail Validation (Simplified)
\npublic static bool IsValidEmail(string email)\n{\n if (string.IsNullOrWhiteSpace(email))\n return false;\