替换另一种模式中的模式

时间:2022-09-13 12:15:48

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?

例如 - 这是目标字符串“并且我想要删除一些”行“中断\ r \ n”而不是其他人\ r \ n。我能这样做吗?

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. 替换另一种模式中的模式

现在我希望能够在这些匹配中找到模式\ r \ n并替换它们,同时将\ r \ n留在引号之外。

1 个解决方案

#1


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

您可以在C#中使用可变宽度环视:

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

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

请参阅RegexStorm.net上的演示(regex101不支持.NET正则表达式)。

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):

输出(仅剩1个换行符):

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

#1


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

您可以在C#中使用可变宽度环视:

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

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

请参阅RegexStorm.net上的演示(regex101不支持.NET正则表达式)。

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):

输出(仅剩1个换行符):

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