10 Basic Regular expressions in C#

Creating regular expressions (regex) can be quite useful for pattern matching, searching and replacing text. Here are ten simple examples of C# code using regular expression patterns to match different kinds of strings:

  1. Match a phone number:
using System;
using System.Text.RegularExpressions;

public class Program {
    public static void Main() {
        string input = "My contact numbers: 123-4567, (234)567890";
        Regex regex = new Regex(@"\(?\d{3}\)?[-.\(\)]?\s*\d{3}[-.\(\)]?\s*\d{4}");
        
        Match match = regex.Match(input);
        if(match.Success) {
            Console.WriteLine($"Matched phone number: {match.Value}");
        } else {
            Console.WriteLine("No matching numbers found.");
        }
    }
}
  1. Validate an email address:
using System;
using System.Text.RegularExpressions;

public class Program {
    public static void Main() {
        string input = "My email is john.doe@example.com";
        
        Regex regex = new Regex(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$");
        
        bool validEmail = regex.IsMatch(input);
        Console.WriteLine($"Is the email address valid? {validEmail}");
    }
}
  1. Match a URL:
using System;
using System.Text.RegularExpressions;

public class Program {
    public static void Main() {
        string input = "Visit http://example.com for more information.";
        
        Regex regex = new Regex(@"http[s]?://[^\s]+");
        
        Match match = regex.Match(input);
        if(match.Success) {
            Console.WriteLine($"Matched URL: {match.Value}");
        } else {
            Console.WriteLine("No matching URLs found.");
        }
    }
}
  1. Replace a date format:
using System;
using System.Text.RegularExpressions;

public class Program {
    public static void Main() {
        string input = "Today's date is 31/12/2021.";
        
        Regex regex = new Regex(@"(\d{2})\/(\d{2})\/(\d{4})");
        Match match = regex.Match(input);
        if(match.Success) {
            // Replace with a desired format, e.g., DD-MM-YYYY
            string replacedDate = $"{match.Groups[3]}-{match.Groups[1].Value}-{match.Groups[2].Value}";
            Console.WriteLine($"Replaced date: {replacedDate}");
        } else {
            Console.WriteLine("No matching dates found.");
        }
    }
}
  1. Match an integer:
using System;
using System.Text.RegularExpressions;

public class Program {
    public static void Main() {
        string input = "The value is 42.";
        
        Regex regex = new Regex(@"\b\d+\b");
        
        Match match = regex.Match(input);
        if(match.Success) {
            Console.WriteLine($"Matched integer: {match.Value}");
        } else {
            Console.WriteLine("No matching integers found.");
        }
    }
}
  1. Find a word starting with β€˜a’:
using System;
using System.Text.RegularExpressions;

public class Program {
    public static void Main() {
        string input = "An apple falls from the tree.";
        
        Regex regex = new Regex(@"(?<=\b)\w*a");
        
        Match match = regex.Match(input);
        if(match.Success) {
            Console.WriteLine($"Matched word: {match.Value}");
        } else {
            Console.WriteLine("No matching words found.");
        }
    }
}
  1. Validate an IPv4 address:
using System;
using System.Text.RegularExpressions;

public class Program {
    public static void Main() {
        string input = "The IP is 192.168.1.1.";
        
        Regex regex = new Regex(@"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)($|(\.[a-zA-Z]{1,})){2}$");
        
        bool validIP = regex.IsMatch(input);
        Console.WriteLine($"Is the IP address valid? {validIP}");
    }
}
  1. Match a word containing β€˜at’ (case insensitive):
using System;
using System.Text.RegularExpressions;

public class Program {
    public static void Main() {
        string input = "That cat sat on my mat.";
        
        Regex regex = new Regex(@"(?i)\b\w*at\b");
        
        Match match = regex.Match(input);
        if(match.Success) {
            Console.WriteLine($"Matched word containing 'at': {match.Value}");
        } else {
            Console.WriteLine("No matching words found.");
        }
    }
}
  1. Replace multiple spaces with a single space:
using System;
using System.Text.RegularExpressions;

public class Program {
    public static void Main() {
        string input = "This   sentence  has too      many     spaces.";
        
        Regex regex = new Regex(@"(?<=\s)\s+(?=\s)");
        
        Match match = regex.Match(input);
        while(match.Success) {
            Console.WriteLine($"Matched sequence: {match.Value}");
            input = input.Replace(match.Value, " ");
            match = regex.Match(input);
        }
        
        string result = input.Trim();
        Console.WriteLine($"Cleaned up sentence: '{result}'");
    }
}
  1. Validate a credit card number:
using System;
using System.Text.RegularExpressions;

public class Program {
    public static void Main() {
        string input = "My credit card is 4111-1111-1111-1111.";
        
        Regex regex = new Regex(@"^(?:\d{4}-){3}\d{4}$");
        
        bool validCardNumber = regex.IsMatch(input);
        Console.WriteLine($"Is the credit card number valid? {validCardNumber}");
    }
}

These examples demonstrate various applications of regular expressions in C#. Make sure to test and adjust your patterns as needed for specific use cases or requirements.