hh的mm正则表达式匹配:mm:字符串中的ss [英] Java Regular Expression Matching for hh:mm:ss in String

查看:191
本文介绍了hh的mm正则表达式匹配:mm:字符串中的ss的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析一个文件,它有基于时间的条目。格式如下:

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;
            }
     }

我希望matcher.find()给出如果它在第一次迭代中返回[00:02:10],在第二次迭代中返回[00:04:50]。

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));
    }        
}

输出

[00:02:10]
[00:04:50]

这篇关于hh的mm正则表达式匹配:mm:字符串中的ss的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆