String: replace the string containing the word

I have a string copied from a mutiline text box. I am looking for a method to replace the entire string containing a specific phrase. For example, the line looks like this:

Lorem ipsum dolor sit amet, 
consectetur adipiscing elit. 
Suspendisse egestas.

So, I would like to find a method to replace the entire line containing, for example, a phrase elit, with a new line enim vehicula pellentesque., so resoult will look like this:

Lorem ipsum dolor sit amet, 
enim vehicula pellentesque. 
Suspendisse egestas.

Is there a quick way to do this?

thank

+3
source share
3 answers
var regex = new Regex(@"^.*\Welit\W.*$", RegexOptions.Multiline);
string result = regex.Replace(original, "enim vehicula pellentesque.");

RegexOptions.Multilineis the key; he says apply ^, (= "start") and $(= "end") to indicate the beginning and end of a line instead of the beginning and end of a line.

\W elit, , , fooelit , foo elit .

+7

, , :

textBox.Lines = textBox.Lines
                       .Select(line => line.Contains("elit") 
                               ? "enim vehicula pellentesque." : line)
                       .ToArray();

, , - :

string text = ...

var lines = from line in text.Split
                 (new[] { Environment.NewLine }, StringSplitOptions.None)
            select line.Contains("elit") ? "enim vehicula pellentesque." : line;

string replacedText = string.Join(Environment.NewLine, lines.ToArray());

: JG , , elit. , string.Contains. , , :

line.Split().Contains("elit") // pseudo-overload of String.Split

fancier (Regex, , ) .

+8
private void button1_Click(object sender, EventArgs e)
    {          
        foreach (var line in textBox1.Lines)
        {
            if (line.Contains("hello"))
            {
               textBox1.Text= textBox1.Text.Replace(line, "This is new line");
            }
        }
    }
+1
source

Source: https://habr.com/ru/post/1790204/


All Articles