Skip to content

Instantly share code, notes, and snippets.

@vaclavbohac
Created June 9, 2011 13:13
Show Gist options
  • Save vaclavbohac/1016703 to your computer and use it in GitHub Desktop.
Save vaclavbohac/1016703 to your computer and use it in GitHub Desktop.
Regular expressions in C#
using System;
using System.Text.RegularExpressions;
class RegexExamples
{
public static void Main()
{
// Simple match.
string[] foo = {"vim", "mvim", "gvim", "emacs"};
foreach (string s in foo) {
if (Regex.IsMatch(s, @"[mg]?vim")) {
/// vim, mvim, gvim
Console.WriteLine(s);
}
}
// Splitting.
string bar = "separated;with;colons";
foreach (string item in Regex.Split(bar, @";")) {
// separated, with, colons
Console.WriteLine(item);
}
// Replacing.
bar = "Hello, World";
bar = Regex.Replace(bar, "Hello", "Goodbye");
// Goodbye, World
Console.WriteLine(bar);
bar = "S o m e s p a c e s h e r e";
bar = Regex.Replace(bar, " ", "");
bar = Regex.Replace(bar, "Some", "No");
// Nospaceshere
Console.WriteLine(bar);
// Modifiers.
bar = "John Doe";
if (Regex.IsMatch(bar, "doe", RegexOptions.IgnoreCase)) {
Console.WriteLine("Thanks god, Mr. Doe is here!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment