Examples

Example 1-9. Simple match

//Find Spider-Man, Spiderman, SPIDER-MAN, etc.
namespace Regex_PocketRef
{
  using System.Text.RegularExpressions;

  class SimpleMatchTest
  {
    static void Main( )
    {
      string dailybugle = "Spider-Man Menaces City!";

      string regex = "spider[- ]?man";
      if (Regex.IsMatch(dailybugle, regex, RegexOptions.
IgnoreCase)) {
      //do something
    }
  }
}

Example 1-10. Match and capture group

//Match dates formatted like MM/DD/YYYY, MM-DD-YY,...
using System.Text.RegularExpressions;

class MatchTest
 {
  static void Main( )
    {
    string date = "12/30/1969";
    Regex r =
       new Regex( @"^(\d\d)[-/](\d\d)[-/](\d\d(?:\d\d)?)$" );

    Match m = r.Match(date);

    if (m.Success) {
      string month = m.Groups[1].Value;
      string day   = m.Groups[2].Value;
      string year  = m.Groups[3].Value;
    }
  }
}

Example 1-11. Simple substitution

//Convert <br> to <br /> for XHTML compliance
using System.Text.RegularExpressions;

class SimpleSubstitutionTest
 {
  static void Main( )
   {
    string text = "Hello world. <br>";
    string regex = "<br>";
    string replacement = "<br />";

    string result =
       Regex.Replace(text, regex, replacement, RegexOptions.
IgnoreCase);
  }
}

Example 1-12. Harder substitution

//urlify - turn URLs into HTML links using System.Text.RegularExpressions; public class Urlify { static Main ( ) { string text = "Check the web site, http://www.oreilly.com/ catalog/regexppr."; string regex = @"\b # start at word boundary ( # capture to $1 (https?|telnet|gopher|file|wais|ftp) : # resource and colon [\w/#~:.?+=&%@!\-] +? # one or ...

Get Regular Expression Pocket Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.