3

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.

3
  • 2
    Can you have escaped quotes within quotes? Commented Jun 22, 2012 at 1:09
  • 1
    Does it need to be regex? I think a simple loop would do the trick with more clarity. Commented Jun 22, 2012 at 1:26
  • @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. Commented Jun 22, 2012 at 2:37

2 Answers 2

8

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

str = Regex.Replace(str, @"""[^""]+""", m => m.Value.Replace(' ', '|'));
Sign up to request clarification or add additional context in comments.

8 Comments

Aww you beat me to it. Any reason you are using 2 quotes inside the "does not match" statement?
I think you meant to use \". I believe "" is the VB escape sequence for double-quotes.
@JonSenchyna no. he used @.
@DelusionalLogic: That's how you escape a quotation mark inside a @ delimited string. You can use the string "\"[^\"]+\"" instead.
@Guffa I still dont get it, your alternative one looks right to me, but i just dont understand those two in there, i might need to play a but more with c# to get it...
|
0
/["][^"]+["]/g

Use this pattern to get the strings that are inside of quotes, then do a replace on those returned strings.

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.