Created
December 18, 2011 10:38
-
-
Save maate/1492998 to your computer and use it in GitHub Desktop.
CaptureEvaluator for .NET Regex Engine
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Text.RegularExpressions; | |
using System.Linq; | |
namespace RegexExtensions.RecursiveReplace | |
{ | |
public static class RegexExtensions | |
{ | |
[Serializable] | |
public delegate string CaptureEvaluator(Capture capture); | |
private static CaptureCollection getCapturesFromGroup(Match match, String groupName = null) | |
{ | |
if (groupName != null) | |
return match.Groups[groupName].Captures; | |
else | |
return match.Captures; | |
} | |
public static String ReplaceRecursive(this Regex self, String input, CaptureEvaluator evaluator, String evaluateCapturesFromGroupName = null) | |
{ | |
var sb = new StringBuilder(); | |
sb.Append(input); | |
MatchCollection matches = self.Matches(input); | |
for(Int32 matchNumber = matches.Count - 1; matchNumber > -1; matchNumber--) | |
{ | |
var match = matches[matchNumber]; | |
var captures = getCapturesFromGroup(match, evaluateCapturesFromGroupName); | |
if (captures != null) | |
{ | |
var capture = captures[0]; | |
if (capture.Value != null) | |
{ | |
var replaceWith = evaluator(capture); | |
if (replaceWith != null) | |
{ | |
sb.Replace(capture.Value, replaceWith, capture.Index, capture.Length); | |
if (sb.ToString() == input) | |
continue; | |
var s = ReplaceRecursive(self, sb.ToString(), evaluator); | |
sb.Remove(0, sb.Length); | |
sb.Append(s); | |
} | |
} | |
} | |
} | |
return sb.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test example: