Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all lines that start with a certain string using java regex?

Tags:

java

regex

There is a text of about 1000 characters.

String text = "bla bla..................
               .........................
               .........................
               file.....................
               .........................
               .........................
               file.....................
               .........................

Some lines start with a word "file". How can I remove ALL such lines? Here is what I tried

text = text.replaceAll("file.*?//n", ""); 
like image 589
Azamat Bagatov Avatar asked Nov 16 '13 20:11

Azamat Bagatov


People also ask

How do you remove lines from a String?

The line break can be removed from string by using str_replace() function.

How do I remove all slashes from a String in Java?

Use replaceAll() method to remove backslash from String in Java. It is identical to replace() method, but it takes regex as argument. Since the first argument is regex, you need double escape the backslash.


1 Answers

You could try the following instead:

text = text.replaceAll("(?m)^file.*", "");
  • (?m): Turns multi-line mode on, so that the start-of-line ^ anchor matches the start of each line.
  • ^: matches the start-of-line.
  • file: Matches the literal file sequence.
  • .* matches everything to the end of line.

So this look for any line that has the word file at the start, then matches the entire line and replaces it with the empty string.

like image 189
Ibrahim Najjar Avatar answered Sep 21 '22 18:09

Ibrahim Najjar