Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to Encode text during Regex.Replace call

Tags:

regex

I have a regex call that I need help with.

I haven't posted my regex, because it is not relevant here. What I want to be able to do is, during the Replace, I also want to modify the ${test} portion by doing a Html.Encode on the entire text that is effecting the regex.

Basically, wrap the entire text that is within the range of the regex with the bold tag, but also Html.Encode the text inbetween the bold tag.

RegexOptions regexOptions = RegexOptions.Compiled | RegexOptions.IgnoreCase;
text = Regex.Replace(text, regexBold, @"<b>${text}</b>", regexOptions);
like image 820
public static Avatar asked Jan 24 '23 03:01

public static


2 Answers

There is an incredibly easy way of doing this (in .net). Its called a MatchEvaluator and it lets you do all sorts of cool find and replace. Essentially you just feed the Regex.Replace method the method name of a method that returns a string and takes in a Match object as its only parameter. Do whatever makes sense for your particular match (html encode) and the string you return will replace the entire text of the match in the input string.

Example: Lets say you wanted to find all the places where there are two numbers being added (in text) and you want to replace the expression with the actual number. You can't do that with a strict regex approach, but you can when you throw in a MatchEvaluator it becomes easy.

public void Stuff()
{
    string pattern = @"(?<firstNumber>\d+)\s*(?<operator>[*+-/])\s*(?<secondNumber>\d+)";
    string input = "something something 123 + 456 blah blah 100 - 55";
    string output = Regex.Replace(input, pattern, MatchMath);
    //output will be "something something 579 blah blah 45"
}

private static string MatchMath(Match match)
{
    try
    {
        double first = double.Parse(match.Groups["firstNumber"].Value);
        double second = double.Parse(match.Groups["secondNumber"].Value);
        switch (match.Groups["operator"].Value)
        {
            case "*":
                return (first * second).ToString();
            case "+":
                return (first + second).ToString();
            case "-":
                return (first - second).ToString();
            case "/":
                return (first / second).ToString();
        }
    }
    catch { }
    return "NaN"; 
}

Find out more at http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx

like image 166
viggity Avatar answered Feb 03 '23 18:02

viggity


Don't use Regex.Replace in this case... use..

foreach(Match in Regex.Matches(...))
{
    //do your stuff here
}
like image 45
Ben Scheirman Avatar answered Feb 03 '23 19:02

Ben Scheirman