C# Regex – Replacing Spaces Inside Strings

c++regex

Using C#, I need a some code to use regular expressions to replace spaces inside of quotes with a pipe character (|). problem is that the string could contain multiple quoted expressions and I only want the spaces inside of quotes.

I tried a few things but I am struggling with how to handle the variable number of words that could be inside of quotes, amongst other things.

Here is some examples of what may be input, and the required output:

"word1 word2"
-> "word1|word2"

"word1 word2" word3 "word4 word5"
-> "word1|word2" word3 "word4|word5"

word1 "word2 word3"
-> word1 "word2|word3"

Any help greatly appreciated, and hopefully I will learn about regular expressions.

Best Answer

Use a regular expresion to find the quotes, and a plain Replace to replace the spaces:

str = Regex.Replace(str, @"""[^""]+""", m => m.Value.Replace(' ', '|'));