Regular expression tips

There are several regular expression I use more often than I thought. This will be a comprehensive list of those expressions.

Get file extension

Useful if you need to replace file extension manually as I did with Xceed component


\.[^\.]+$

Check if the input string is UK Post code


[A-Za-z][A-Za-z]?[0-9][0-9]?[A-Za-z]?([A-Za-z]\s?[0-9][A-Za-z][A-Za-z])?

  • Clean up special characters that can break javascript function parameter
    [\x00-\x09\x0B\x0C\x0E-\x1F\x27\x7F\x5C]|<[^>]*>|\s+
  • _cleanupRegEx = new Regex(@"[\x00-\x09\x0B\x0C\x0E-\x1F\x27\x7F\x5C]|<[^>]*>|\s+", RegexOptions.Compiled)
    

    Those hx codes are a bit unfriendly. Please use the below table for your reference.
    www.asciitable.com

    Named group

    var titleRegex = new Regex("<title>(?<title>.*?)</title>", RegexOptions.IgnoreCase);
    var contentRegex = new Regex("<content>(?<content>.*?)</content>", RegexOptions.IgnoreCase);
    
    var page = new DataPage();
    
    var titleMatch = titleRegex.Match(content);
    page.Title = titleMatch.Groups["title"].Value;
    
    var contentMatch = contentRegex.Match(content);
    page.Content = contentMatch.Groups["content"].Value;
    
    
    Regular expression tips