User Tools

Site Tools


notes:csharp:regex

Regular Expressions in C#

Example: Simple examples:

using System.Text.RegularExpressions;
...
// Check if all characters are numeric.
Regex reg = new Regex(@"^\d+$");
bool b1 = reg.Match("3451").Success; // true
bool b2 = reg.Match("34a1").Success; // false
 
// Check if a string has letters a,A,b,B.
bool b3 = Regex.IsMatch("acd", "a|b", RegexOptions.IgnoreCase); // true
bool b4 = Regex.IsMatch("eBd", "a|b", RegexOptions.IgnoreCase); // true
bool b5 = Regex.IsMatch("efg", "a|b", RegexOptions.IgnoreCase); // false
 
// Modify a string.
string s1 = Regex.Replace("aib", "a|b", "X"); // XiX

Example: Extract email addresses from a string:

public List<string> GetEmails(string str)
{
    const string Pattern = @"[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}";
    List<string> emails = new List<string>();
 
    Regex reg = new Regex(Pattern, RegexOptions.IgnoreCase);
    MatchCollection matches = reg.Matches(str);
    foreach (Match m in matches)
        emails.Add(m.Value);
 
    return emails;
}
...
string emailsStr = "leon@micro.com john@ Mel@kata.ca Phil@@lego.com";
List<string> emails = GetEmails(emailsStr); // emails = { "leon@micro.com", "Mel@kata.ca" }

Example: Use named groups to match patterns:

string str = @"Leon's GDI+ GDI++ +GDU Mike'ss Kale's Chloe''s";
Regex re = new Regex(@"((?<GroupPlusSign>\w+\+)|(?<GroupApostrophe>\w+'s))(?=(\s|$))", RegexOptions.None);
MatchCollection matches = re.Matches(str); // 3 matches: Leon's GDI+ Kale's
 
int i = 1;
foreach (Match m in matches)
{
    Console.WriteLine($"Match #{i}: " +
        $"GroupPlusSign={m.Groups["GroupPlusSign"].Value}, " +
        $"GroupApostrophe={m.Groups["GroupApostrophe"].Value}");
    ++i;
}

Output:

Match #1: GroupPlusSign=, GroupApostrophe=Leon's
Match #2: GroupPlusSign=GDI+, GroupApostrophe=
Match #3: GroupPlusSign=, GroupApostrophe=Kale's
notes/csharp/regex.txt · Last modified: 2016/12/13 by admin