如何使用java正则表达式删除以某个字符串开头的所有行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20023695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove all lines that start with a certain string using java regex?
提问by Azamat Bagatov
There is a text of about 1000 characters.
有大约 1000 个字符的文本。
String text = "bla bla..................
.........................
.........................
file.....................
.........................
.........................
file.....................
.........................
Some lines start with a word "file". How can I remove ALLsuch lines? Here is what I tried
有些行以单词“file”开头。如何删除所有这些行?这是我尝试过的
text = text.replaceAll("file.*?//n", "");
采纳答案by Ibrahim Najjar
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 literalfile
sequence..*
matches everything to the end of line.
(?m)
:打开多行模式,以便行首^
锚点与每行的开头相匹配。^
: 匹配行首。file
: 匹配文字file
序列。.*
匹配到行尾的所有内容。
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.
所以这会查找任何以单词file
开头的行,然后匹配整行并将其替换为空字符串。