字符串中 hh:mm:ss 的 Java 正则表达式匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19029880/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:33:06  来源:igfitidea点击:

Java Regular Expression Matching for hh:mm:ss in String

javaregextime

提问by DareDevil

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.

我希望当“matcher.find()”为真时,它在第一次迭代中返回 [00:02:10],在第二次迭代中返回 [00:04:50]。

采纳答案by rolfl

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]

回答by Boris the Spider

Don't use regex for this, use a SimpleDateFormat. This has two massive advantages

不要为此使用正则表达式,请使用SimpleDateFormat. 这有两个巨大的优势

  1. The code in SimpleDateFormatis tested and robust
  2. The SimpleDateFormatwill validate to ensure that you have real time numbers
  1. 中的代码SimpleDateFormat经过测试且健壮
  2. SimpleDateFormat会进行验证,以确保您有实时的数字

This would look something like this:

这看起来像这样:

public static void main(String[] args) throws Exception {
    final String s = "00:02:10-XYZ:Count=10\n"
            + "00:04:50-LMK:Count=3";
    final Scanner sc = new Scanner(s);
    final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    while(sc.hasNextLine()) {
        final String line = sc.nextLine();
        final Date date = dateFormat.parse(line);
        final Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        System.out.println(calendar.get(Calendar.HOUR));
        System.out.println(calendar.get(Calendar.MINUTE));
        System.out.println(calendar.get(Calendar.SECOND));
    }
}

Output:

输出:

0
2
10
0
4
50

From the javadoc for DateFormat.parse:

来自javadoc 的DateFormat.parse

Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.

从给定字符串的开头解析文本以生成日期。该方法可能不会使用给定字符串的整个文本。

So the SimpleDateFormatwill parse the Stringuntil it reads the whole pattern specified then stops.

因此SimpleDateFormat将解析String直到它读取指定的整个模式然后停止。

回答by Anirudha

SimpleDateFormat dateFormat = new SimpleDateFormat("KK:mm:ss");    
Pattern pattern = Pattern.compile("\d+:\d+:\d+");
Matcher matcher;
List<Date> listMatches = new ArrayList<Date>();
for(int x = 0; x < file_content.size(); x++)
{
    matcher= pattern.matcher(file_content.get(x));
    while(matcher.find())
    {
        Date temp=null;
        try{temp=dateFormat.parse(matcher.group(0));}catch(ParseException p){}
        if(temp!=null)
        listMatches.add(temp);
    }
}

回答by DareDevil

I did with this way.

我是用这种方法做的。

00:02:10-XYZ:Count=10
00:04:50-LMK:Count=3

Pattern pattern = Pattern.compile("([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])");
//File Beginning Time
for(int x = 0; x < file_content.size(); x++)
   {
        matcher= pattern.matcher(file_content.get(x));
        ListMatches = new ArrayList<String>();
        if(matcher.find())
          {
                start_time = matcher.group();
                break;
          }                
    }
//File End Time
for(int x = file_content.size()-1; x > 0 ; x--)
        {
            matcher= pattern.matcher(file_content.get(x));
            listMatches = new ArrayList<String>();
            if(matcher.find())
            {
                end_time = matcher.group();
                break;
            }                  
        }