1

I am having trouble doing the following search and replace:

// Consider this string - Note that it may be much more complicated, with many more matches
string output = "\"$type\": \"SomeType\",";

// The variable to search and replace - In this case is set to "SomeType"
string myType = "SomeType";

// The non-working regex
output = Regex.Replace(output, @"\"\$type\"\:\s\"" + myType + @"\",", "NewType");

I would expect the following output:

"$type": "NewType",

instead of:

"$type": "SomeType",

I think there are 2 problems here, but I cannot figure out the syntax. One is the use of the string "type", the other one is that I am not using capture groups so that only myType gets replaced by "NewType" in the output string.

0

1 Answer 1

1

You want to use

output = Regex.Replace(output, $@"(?<=""\$type"":\s""){Regex.Escape(myType)}(?="",)", "NewType");

See the C# demo.

NOTES:

  • " must be escaped with another " in a verbatim string literal
  • Escape the variables inside regex patterns
  • Use lookarounds to wrap the pattern parts you need to keep after substitution.

The resulting regex looks like (?<="\$type":\s")NewType(?=",) and matches

  • (?<="\$type":\s") - a location that is immediately preceded with "$type": a whitespace and "
  • NewType - some text
  • (?=",) - a location that is immediately followed with ",.
Sign up to request clarification or add additional context in comments.

4 Comments

Ouha, much trickier than I thought, thanks a lot!
What if myType was defined in the following line of the string, but had to be inserted as previously done? Can I do something of the sort: Regex.Replace(g, $@"(?<=""\$type"":\s""){"AString"}("",\s*\n\s*""Name"":\s""{myVariable}?="",)", myVariable, RegexOptions.IgnoreCase);
@stackMeUp You may use any amount of variables in the regex pattern.
Thank, I figured it out :-)

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.