Gun
Gun

Reputation: 1411

How to remove newline characters from double quotes?

I have a scenario like this:

"abcdef
 123sq
 gh"

should be rearranged as "abcdef 123sq gh".

For this I used regular expressions and it works fine:

Match match = Regex.Match(myString, @""".*""", RegexOptions.Singleline);
if (match.Success) {
  myString= myString.Replace(match.Value, match.Value.Replace("\n", ""));
}

But this is not working for the scenario below:

"abc" "def"
asdf123456
"abc"

In the example above, it considers the first and last quotes and it returns the 3 lines as one.

Upvotes: 1

Views: 1583

Answers (4)

I4V
I4V

Reputation: 35373

var newstring = Regex.Replace(myString, 
                                @"\""[^\""]*?[\n\r]+[^\""]*?\""", 
                                m=>Regex.Replace(m.Value,@"[\n\r]",""));

This will convert

"abc" "d
 ef"
asdf123456
"ghi"

to

"abc" "d ef"
asdf123456
"ghi"

of course it works for your sample too.

Upvotes: 2

Habib
Habib

Reputation: 223422

Use string.Replace like:

For you comment:

But i want to replace new line within the double quotes

myString = myString.Replace(Environment.NewLine, "\"");

Upvotes: 5

Oded
Oded

Reputation: 499382

You should be able to simply replace new lines with a double quote:

myString = myString.Replace(Environment.NewLine, "\"");

Upvotes: 7

Grhm
Grhm

Reputation: 6864

Your code matches any characters between quotes, but is a greedy expression - i.e. it matches as many character as possible, which sometimes means matching multiple lines.

If you use a non-greedy expression it will match a few characters a possible. Use:

Match match = Regex.Match(myString, @""".*?""", RegexOptions.Singleline);

Upvotes: 1

Related Questions