nzdev
nzdev

Reputation: 41

Replace a pattern that is within another pattern

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

Upvotes: 0

Views: 49

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

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?

Upvotes: 2

Related Questions