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 textIn 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 textApparently, the .*'s aren't grabbing the newlines as it only replaced text on the same line.
- How can I make the .*'s grab over newlines?
- 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");
精彩评论