0

I need some help replacing only a portion of a string that I match with regex. For example, I have the following text:

This is some sentence
and the continuation of the sentence

I need to find new line characters such that it is preceded by a word and proceeded by a word, so I use the following regex:

Regex rgx = new Regex("\w\n\w");

When I find this condition, I want to replace ONLY the newline with a space. So the output would look like this:

This is some sentence and the continuation of the sentence

Is it possible to do this?

UPDATE 12/11/14:

This question was marked as a duplicate, however, the referenced solution was not exactly what I was looking for. As stated above, it needs to be the scenario where a new line is preceded and proceeded by a character. The referenced solution just catches all '\n' characters and replaces it with an empty string.

Here was the solution for my problem:

string input = "This is some sentence\nand the continuation of the sentence",
       pattern = @"(\w)\n(\w)",
       replacement = "$1 $2",
       output = string.Empty;

output = Regex.Replace(input, pattern, replacement);

The result of this would be:

This is some sentence and the continuation of the sentence

My solution was inspired by this solution.

Community
  • 1
  • 1
Anthony
  • 806
  • 7
  • 14
  • It can't just be any newline. It must be a newline that is immediately preceded and proceeded by actual text characters. – Anthony Dec 10 '14 at 18:43

1 Answers1

0

Split the string up and set it back together with new joints. You could do something like that:

string input = "This is a sentence\nand the continuation of the sentence.\n\nLet's go for\na second time.";

var rx = new Regex(@"\w(\n)\w");

var output = new StringBuilder();

int marker = 0;

var allMatches = rx.Matches(input);
foreach (var match in allMatches.Cast<Match>())
{
    output.Append(input.Substring(marker, match.Groups[1].Index - marker));
    output.Append(" ");
    marker = match.Groups[1].Index + match.Groups[1].Length;
}
output.Append(input.Substring(marker, input.Length - marker));

Console.WriteLine(output.ToString());
lzydrmr
  • 867
  • 5
  • 7