0

Is it possible to replace a named match by some constant value or another named match? Lets say I have input string and if it contains "123" replace "123" by "567" if the string has "234" I want it replace by "678". I need to do that using Regex.Replace as I use API which uses Regex.Replace and changing that API is not what I want.

So what I provide for that API matchPattern & replacePattern to get something like that:

Regex.Replace("123", matchPattern, replacePattern) returns "567"

Regex.Replace("234", matchPattern, replacePattern) returns "678"

2
  • So what you're saying is that you want to pass in a single, fixed replacePattern that does different things depending on the input? Commented Nov 21, 2012 at 7:10
  • 1
    Why not just execute two Regex.Replace commmands? Commented Nov 21, 2012 at 13:30

2 Answers 2

2

This is not possible with just a regex replace call. But you can provide a callback function:

public String Replacer(Match m) {
    if (m.Groups[0].Value == "123")
       return "567";
    else if (m.Groups[0].Value == "456")
       return "678";
}

resultString = Regex.Replace(subject, @"\b(?:123|456)\b", new MatchEvaluator(Replacer));
Sign up to request clarification or add additional context in comments.

Comments

1

I expect there would some others ways to do this, but i came up with the following approach that uses named groups and anonymous methods.

I have assumed in my example that 123, 456, 789 will be replaced with 111, 444, 777 respectively while 000 will remain intact in the string.

I have used an approach to name the group a value that will be a use as a replacement value. For example here in this part:

(?<111>123) = value 123 will be replace by 111 where 111 is also the name of the group.

So, a general pattern would become: (?<ValueToReplace>ValueToSearch)

Here is a sample code:

Dim sampleText = "123 456 789 000"
Dim re As New Regex("\b(?<111>123)\b|\b(?<444>456)\b|\b(?<777>789)\b")
Dim count As Integer = re.Matches(sampleText).Count
Dim contents As String = re.Replace(sampleText, New MatchEvaluator(Function(c) re.GetGroupNames().Skip(1).ToArray().GetValue(c.Captures(0).Index Mod count).ToString()))

From your approach I expect you work in VB.Net but i have attached a C# version too.

Here, is the C# version:

var sampleText = @"123 456 789 000";
Regex re = new Regex(@"\b(?<111>123)\b|\b(?<444>456)\b|\b(?<777>789)\b");
int count = re.Matches(sampleText).Count;
string contents = re.Replace(sampleText, new MatchEvaluator((c) => re.GetGroupNames().Skip(1).ToArray().GetValue(c.Captures[0].Index % count).ToString()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.