3
votes

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.

2
Can you have escaped quotes within quotes? - Jon Senchyna
Does it need to be regex? I think a simple loop would do the trick with more clarity. - Sergey Kalinichenko
@dasblinkenlight - Completely agree. Whenever I have to deal with tokenizing quoted strings a loop is always easier to debug and read later. It's only a couple lines of code and will perform better too. - Josh

2 Answers

8
votes

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

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

There is a helpful webiste to test stuff like this, it's called reFiddle

http://refiddle.com

What i would do is to use this

http://refiddle.com/288

/["][^"]+["]/g

To get the strings that are inside of quotes, then just do a replace on those returned strings, and you should be golden.