如何使用正则表达式仅去除双引号内的“ \ n”字符

时间:2019-12-17 05:47:18

标签: c# regex

文本样式将是这样

\n "this is some text \n this should not be on the new line"

我只想检测双引号内的\n并去除它。 因此最终结果将是

\n "this is some text this should not be on the new line"

3 个答案:

答案 0 :(得分:1)

尝试类似fiddle

的方法
using System;
using System.Text.RegularExpressions;

public class Simple
{
    static string StripLinefeeds(Match m)
    {
        string x = m.ToString(); // Get the matched string.
        return x.Replace("\n", "");
    }

    public static void Main()
    {
        Regex re = new Regex(@""".+?""", RegexOptions.Singleline);
        MatchEvaluator me = new MatchEvaluator(StripLinefeeds);     
        string text = "\n\"this is some text \n this should not be on the new line\"";
        Console.WriteLine(text);
        text = re.Replace(text, me);
        Console.WriteLine(text);
        text = "\n\"this is some \n text \n\n\n this should not be \n\n on the new line\"";
        Console.WriteLine(text);
        text = re.Replace(text, me);
        Console.WriteLine(text);
    }
}

答案 1 :(得分:0)

此模式可能适合您。

build

这是配对的“后视” /(?<=(\"(.|\n)*))(\n(?=((.|\n)*\")))/g 和“前视” (?<=(\"(.|\n)*))(...)。不过最多只能使用一对引号,因此,如果您的需求发生变化,则必须对此进行调整。

答案 2 :(得分:0)

我认为这是最简单的方法:

匹配("\w.[^\\]+)\\n ?

并替换为\1

https://regex101.com/r/8UXMzZ/3