开发者

Have a regular expression work over newlines Java

I have some output, which looks like this:

blah blah garbage text

more garbage text which doesn't matter

Duration: 00:0开发者_高级运维2:55.34, start: 0.000000, bitrate: 4097 kb/s

some more garbage text

even more garbage text

In java, I'm using a regular expression to turn this line into plain old

00:02:55.34

but it is not replacing the lines at the top and bottom. Using this line of code:

String durationString = s.replaceAll(".*Duration: (\\d\\d:\\d\\d:\\d\\d(\\.\\d\\d?)?).*", "$1");  

results in this:

blah blah garbage text

more garbage text which doesn't matter

00:02:55.34

some more garbage text

even more garbage text

Apparently, the .*'s aren't grabbing the newlines as it only replaced text on the same line.

  1. How can I make the .*'s grab over newlines?
  2. If 1. isn't possible, is there any way to do what I need, assuming I don't know how many lines of garbage text are at the top and bottom?


You need to set the dot-all flag:

String durationString = s.replaceAll("(?s).*Duration: (\\d\\d:\\d\\d:\\d\\d(\\.\\d\\d?)?).*", "$1");  


You need to use the Pattern.DOTALL flag to say that . should match newlines. or specify the flag in the pattern using (?s) e.g.

String regex = "(?s).*Duration: (\\d\\d:\\d\\d:\\d\\d(\\.\\d\\d?)?).*";


Try this:

String durationString = s.replaceAll(".*Duration: (\\d\\d:\\d\\d:\\d\\d(\\.\\d\\d?)?).*|.*", "$1");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜