How to delete the entire line if it has a word?

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

 textBox1.Text = Regex.Replace(textBox1.Text, "word", ""); 
+6
source share
2 answers

Assuming you mean strings, as I 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); 

In the above case, the line starting with "massa, malesuada ..." is deleted because it contains "nisl".

Mandatory LINQ method (reusing the 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 need to use Regex, but regex has \b , which makes word search easy. IndexOf will work too, but you may have to worry about finding "over" in "stackoverflow" (for example).

+6
source

If the text box contains your word, replace the entire line of text with an empty line:

 textBox1.Text = textBox1.Text.IndexOf("word") < 0 ? textBox1.Text : ""; 
0
source

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


All Articles