Regular expression tips

less than 1 minute read

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


  • Clean up special characters that can break javascript function parameter
  • </code>

    [sourcecode language="csharp"]
    _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.

    Named group

    [sourcecode language="csharp"]
    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;