Reputation: 55
We have a text which goes like this ..
This is text
i want
to keep
but
Replace this sentence
because i dont like it.
Now i want to replace this sentence Replace this sentence because i dont like it.
Of course going like this
text = text.Replace(@"Replace this sentence because i dont like it.", "");
Wont solve my problem. I can't drop line breaks and replace them with one line.
My output should be
This is text
i want
to keep
but
Please keep in mind there is a lot variations and line breaks for sentence i don't like.
I.E it may go like
Replace this
sentence
because i dont like it.
or
Some text before. Replace this
sentence
because i dont like it.
Upvotes: 0
Views: 371
Reputation: 112279
You can use Regex to find any kind of whitespace. This includes regular spaces but also carriage returns and linefeeds as well as tabulators or half-spaces and so on.
string input = @"This is text
i want
to keep
but
Replace this sentence
because i dont like it.";
string dontLike = @"Replace this sentence because i dont like it.";
string pattern = Regex.Escape(dontLike).Replace(@"\ ", @"\s+");
Console.WriteLine("Pattern:");
Console.WriteLine(pattern);
string clean = Regex.Replace(input, pattern, "");
Console.WriteLine();
Console.WriteLine("Result:");
Console.WriteLine(clean);
Console.ReadKey();
Output:
Pattern:
Replace\s+this\s+sentence\s+because\s+i\s+dont\s+like\s+it\.
Result:
This is text
i want
to keep
but
Regex.Escape
escapes any character that would otherwise have a special meaning in Regex. E.g., the period "."
means "any number of repetitions". It also replaces the spaces " "
with @"\ "
. We in turn replace @"\ "
in the search pattern by @"\s+"
. \s+
in Regex means "one or more white spaces".
Upvotes: 3
Reputation: 361
You can use something like this, if output format of string is optional here:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string textToReplace = @"Replace this sentence because i dont like it.";
string text = @"This is text
i want
to keep
but
Replace this sentence
because i dont like it.";
text = Regex.Replace(text, @"\s+", " ", RegexOptions.Multiline);
text = text.Replace(textToReplace, string.Empty);
Console.WriteLine(text);
}
}
Output:
"This is text i want to keep but"
Upvotes: 0
Reputation: 781
Or, use LINQ to accomplish this:
var text = "Drones " + Environment.NewLine + "are great to fly, " + Environment.NewLine + "yes, very fun!";
var textToReplace = "Drones are great".Split(" ").ToList();
textToReplace.ForEach(f => text = text.Replace(f, ""));
Output:
to fly,
yes, very fun!
Whatever method you choose, you are going to deal with extra line breaks, too many spaces and other formatting issues... Good luck!
Upvotes: 1
Reputation: 100527
Use regex to match "any whitespace" instead of just space in your search string. Roughly
"\s+"
(reference)Upvotes: 1