I am parsing a file and it has time based entries in it. format is like:
00:02:10-XYZ:Count=10
00:04:50-LMK:Count=3
Here what I want is to extract the time value from string line
I have searched many links and couldn't find out the thing what I want, eventually I have written this code.
Pattern pattern = Pattern.compile("((?i)[0-9]{1,2}:??[0-9]{0,2}:??[0-9]{0,2})"); //(?i)[0-9]{1,2}:??[0-9]{0,2}:??[0-9]{0,2} //\\d{1,2}:\\d{1,2}:\\d{1,2}
Matcher matcher;
List<String> listMatches;
Below is the loop where I apply logic
for(int x = 0; x < file_content.size(); x++)
{
matcher= pattern.matcher(file_content.get(x));
listMatches = new ArrayList<String>();
while(matcher.find())
{
listMatches.add(matcher.group(1));
break;
}
}
I want when "matcher.find()" gives true it returns me [00:02:10] in first iteration and [00:04:50] in 2nd iterations.
Seems like an unnecessarily complicated pattern.... why not just (if you are doing line-by-line processing):
"^(\\d\\d:\\d\\d:\\d\\d)"
If you are doing multi-line processing you will want to use:
"(?m)^(\\d\\d:\\d\\d:\\d\\d)"
Here's some example code and output:
public static void main(String[] args) {
final Pattern pattern = Pattern.compile("(?m)^(\\d\\d:\\d\\d:\\d\\d)");
final Matcher matcher = pattern.matcher("00:02:10-XYZ:Count=10\n00:04:50-LMK:Count=3");
while(matcher.find())
{
System.out.printf("[%s]\n", matcher.group(1));
}
}
outputs
[00:02:10]
[00:04:50]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With