1

I have dictionary with key as pattern and replacement as value. Each pattern have one capturing group. I would like to replace ONLY capturing group with the replacement. My attempt is the following, but of course it's replacing whole pattern. I am limited to .NET 3.5. Not sure if I am on right track.

        string xml = "abc def ghi blabla horse 123 jakljd alj ldkfj s;aljf kljf sdlkj flskdjflskdjlf lskjddhcn guffy";
        Dictionary<string, string> substitutions = new Dictionary<string, string> 
        { 
            {"abc (.+) ghi", "AAA"},
            {"kljf (.+) flskdjflskdjlf", "BBB"}
        };

        foreach(KeyValuePair<string, string> entry in substitutions)
        {
            xml = Regex.Replace(xml, entry.Key, delegate(Match m) { return m.Groups[1].Value; });
            Console.WriteLine(xml);
        }

The final string should like this:

"abc AAA ghi blabla horse 123 jakljd alj ldkfj s;aljf BBB sdlkj flskdjflskdjlf lskjddhcn guffy"

2 Answers 2

1

You need to use lookarounds.

"(?<=abc ).+(?= ghi)", "AAA"

This will enable you to replace the words you want.You dont need capture group

Sign up to request clarification or add additional context in comments.

Comments

0

Use positive loohbehind and lookaheads:

string xml = "abc def ghi blabla horse 123 jakljd alj ldkfj s;aljf kljf sdlkj flskdjflskdjlf lskjddhcn guffy";
Dictionary<string, string> substitutions = new Dictionary<string, string> 
{ 
    {@"(?<=abc\s).+(?=\sghi)", "AAA"},
    {@"(?<=kljf\s).+(?=\sflskdjflskdjlf)", "BBB"}
};

foreach (KeyValuePair<string, string> entry in substitutions)
{
    xml = Regex.Replace(xml, entry.Key, entry.Value);
    Console.WriteLine(xml);
}

They are zero-width assertions, i.e., they are required to satisfy the match, but won't be included in the result.

3 Comments

This basically the same what vks suggests.
Isnt this the same as my answer?
@stribizhev Yes, the idea is the same, however I started writing this answer about 30 seconds after the question was asked, and I usually take my time writing a relatively complete answer, disliking the fastest gun in the west approach, and during that time fast guns might shoot an answer with the same concept, however I still post my answer when I'm done FWIW.

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.