Devel
Devel

Reputation: 960

String: replace a line which contains a word

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

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

So I would like to find a method to replace the whole line that contains for example phrase elit with the new line enim vehicula pellentesque. so the resoult would be:

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

Is there a quick way to do it?

Thanks

Upvotes: 3

Views: 10587

Answers (3)

Ani
Ani

Reputation: 113472

If you're looking to replace all lines that contain that text, you could do:

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

If you're dealing with just the string representing the lines, you could do something along the lines of:

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());

EDIT: As JG points out in a comment, this won't work if you're looking for the specific word elit. In this case, you'll need a different predicate than a simple string.Contains. For example, you could just split the line by all whitespace characters and check if one of them is the blacklisted word:

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

You may need a fancier filter (Regex such as in Domenic's answer) depending on your definition of 'word'.

Upvotes: 8

Javed Akram
Javed Akram

Reputation: 15354

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");
            }
        }
    }

Upvotes: 1

Domenic
Domenic

Reputation: 112917

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

RegexOptions.Multiline is key; it says to apply ^, ( = "beginning") and $ ( = "end") to mean beginning and end of line, instead of beginning and end of string.

The \Ws look for non-word characters on either side of elit, so e.g. fooelit will not match but foo elit will.

Upvotes: 9

Related Questions