0

I want to be able to replace a line break (actually remove) but only if they exist within quotes.

The string below should have the line breaks in bold removed as they are inside quotes:

eg - This is the target string "and I \r\n want some" line "breaks \r\n" to be removed but not others \r\n. Can I do that?

See image below for regex pattern. I can isolate the quotes that have line breaks in them.

Now I want to be able to find the pattern \r\n within these matches and replace them, while leaving \r\n outside of quotes alone. enter image description here

1
  • 2
    Don't post screenshots of text, we can't copy+paste that. Commented May 4, 2015 at 22:56

1 Answer 1

2

You can use the variable-width look-arounds in C#:

(?<="[^"]*)\\r\\n(?=[^"]*")

See demo on RegexStorm.net (regex101 does not support .NET regex).

In case you want to remove actual whitespace, you can use

(?<="[^"]*)[\r\n]+(?=[^"]*")

Sample code:

var rx = new Regex(@"(?<=""[^""]*)[\r\n]+(?=[^""]*"")");
var removed = rx.Replace("This is the target string \"and I \r\n want some\" line \"breaks \r\n\" to be removed but not others \r\n. Can I do that?", string.Empty);

Output (only 1 linebreak remains):

This is the target string "and I  want some" line "breaks " to be removed but not others 
. Can I do that?
Sign up to request clarification or add additional context in comments.

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.