Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the whole line if a word exists in it?

Tags:

c#

I know how to replace word with Regex, but I have no idea how to remove/replace the whole line if the word exists in it.

textBox1.Text = Regex.Replace(textBox1.Text, "word", "");
like image 869
Little Fox Avatar asked May 17 '15 20:05

Little Fox


1 Answers

Assuming you mean lines as I've understood them:

var text =  String.Join(Environment.NewLine, new[]{
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec sed congue tortor, ",
        "ut sollicitudin lacus. Vestibulum ante ipsum primis in faucibus orci luctus et ",
        "ultrices posuere cubilia Curae; Nam ultricies dolor vel massa scelerisque, et interdum ",
        "orci finibus. Duis felis nibh, pretium quis placerat at, fringilla eu justo. ",
        "Pellentesque id nunc ullamcorper, condimentum lacus a, mollis neque. Etiam sapien ",
        "massa, malesuada in dui in, rutrum aliquet nisl. Sed a egestas odio, in faucibus ",
        "magna. Morbi sit amet tincidunt diam. Morbi tristique magna diam, nec consectetur ",
        "mauris vehicula volutpat. Praesent egestas cursus arcu, vel luctus purus interdum eget. ",
        "Pellentesque nec bibendum orci. Proin eget odio mattis, euismod nulla ac, fermentum ",
        "ipsum. Aliquam a velit nulla. Suspendisse eget posuere nunc, at imperdiet ligula. ",
        "Pellentesque vel risus eu augue sagittis faucibus. Sed leo tellus, auctor id eros ut, ",
        "posuere consequat ligula. "
    });
    var word = "nisl";
    var result = Regex.Replace(text, String.Format(@"(^.*?\b{0}\b.*?$)", Regex.Escape(word)), "", RegexOptions.Multiline | RegexOptions.IgnoreCase);

This the above case, the line beginning "massa, malesuada..." has been removed since it contains "nisl".

Obligatory LINQ method (re-using text variable above):

var regex = new Regex(String.Format(@"\b{0}\b", Regex.Escape(word)), RegexOptions.IgnoreCase);
var result = String.Join(Environment.NewLine, text.Split(new String[]{ Environment.NewLine }, StringSplitOptions.None)
    /* remove line */ .Where(line => !regex.IsMatch(line))
    /* replace line */ //.Select(line => !regex.IsMatch(line) ? line : "" /* replacement*/)
    .AsEnumerable()
).Dump("LINQ");

And you don't have to use Regex, but regex does have \b which makes finding words an easy thing. IndexOf would work, too, but you may have to worry about finding "over" within "stackoverflow" (for example).

like image 164
Brad Christie Avatar answered Nov 11 '22 19:11

Brad Christie