Created
February 23, 2015 17:07
-
-
Save jonny-novikov/6289af322b9fa0be9011 to your computer and use it in GitHub Desktop.
C# equivalent to preg_match and preg_replace
This file contains 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
/// <summary> | |
/// .NET C# equivalent to PHP preg_match and preg_replace | |
/// </summary> | |
public static class RegexExtensions | |
{ | |
/// <summary> | |
/// Equivalent to PHP preg_match but only for 3 requied parameters | |
/// </summary> | |
/// <param name="regex"></param> | |
/// <param name="input"></param> | |
/// <param name="matches"></param> | |
/// <returns></returns> | |
public static bool preg_match(this Regex regex, string input, out List<string> matches) | |
{ | |
var match = regex.Match(input); | |
var groups = (from object g in match.Groups select g.ToString()).ToList(); | |
matches = groups; | |
return match.Success; | |
} | |
/// <summary> | |
/// Equivalent to PHP preg_replace | |
/// <see cref="http://stackoverflow.com/questions/166855/c-sharp-preg-replace"/> | |
/// </summary> | |
/// <param name="input"></param> | |
/// <param name="pattern"></param> | |
/// <param name="replacements"></param> | |
/// <returns></returns> | |
public static string preg_replace(this string input, string[] pattern, string[] replacements) | |
{ | |
if (replacements.Length != pattern.Length) | |
throw new ArgumentException("Replacement and Pattern Arrays must be balanced"); | |
for (var i = 0; i < pattern.Length; i++) | |
{ | |
input = Regex.Replace(input, pattern[i], replacements[i]); | |
} | |
return input; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice!