Created
June 9, 2011 13:13
-
-
Save vaclavbohac/1016703 to your computer and use it in GitHub Desktop.
Regular expressions in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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