0

The text patten would be like this

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

I want to detect only the \n that is inside the double quotes and have it stripped out. So the end result would be

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

Frostless
  • 818
  • 1
  • 11
  • 33
  • I think that is splitting the string on the "the \n that is inside the double quotes", excluding the seperator. Regex is more about "finding things that match", then "excluding things that do not match". But I have very little skill with regex, so I could be wrong. – Christopher Dec 17 '19 at 05:48
  • Does the answer have to solve it only by using regex? – smoksnes Dec 17 '19 at 06:26
  • https://stackoverflow.com/questions/10805125/how-to-remove-all-line-breaks-from-a-string – Joel Wiklund Dec 17 '19 at 06:33
  • `string result = Regex.Replace(Regex.Matches(text, "[^\"]+")[1].Value, "\n", " ");` (just one possible way. It allows to inspect the match collection, eventually, to see whether the first char is actually a line feed). – Jimi Dec 17 '19 at 07:34
  • * *In case the quoted text may contain more than one line feed* – Jimi Dec 17 '19 at 07:55

3 Answers3

1

Try something like this 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);
    }
}
0

This pattern might work for you.

/(?<=(\"(.|\n)*))(\n(?=((.|\n)*\")))/g

This is a "look-behind" (?<=(\"(.|\n)*))(...) and a "look-ahead" \n(?=((.|\n)*\")) paired together. It will only be reliable with one pair of quotes at most though, so if your needs change, you will have to adjust for that.

chris
  • 789
  • 4
  • 16
0

I think this would be the simplest way:

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

And replace with \1

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

CAustin
  • 4,525
  • 13
  • 25