首页 > 解决方案 > 如何在 Java 中的一行中输入时间?

问题描述

问题出在Java

我想花时间输入如下

12:00 AM 11:42 PM

将有一系列这样的输入,直到N行。

这里给出了两个不同的时间输入

1)12:00 AM

2)11:42 PM

但他们在同一行。

时间输入适用于单人进入(12:00 AM)和离开(11:42 PM)

我知道SimpleDateFormat,但我不能修改它以满足我所说的需要。

所以请帮忙

标签: javaalgorithmdatetimedatetime-parsingtimeofday

解决方案


对于上述问题,正则表达式对于从输入字符串/文本中查找和收集值非常有帮助。如下所示。

public static void main(String[] args) {
        String input = "12:00 AM 11:42 PM";
        ArrayList<String> list = new ArrayList();
        Pattern pattern = Pattern.compile("[\\d:]*[ ](AM|PM)");
          //Matching the compiled pattern in the String
          Matcher matcher = pattern.matcher(input);
          while (matcher.find()) {
             list.add(matcher.group());
          }
          Iterator<String> it = list.iterator();
          System.out.println("List of matches: ");
          while(it.hasNext()){
             System.out.println(it.next());
          }
    }

这里我们有输入字符串包含时间。然后我们使用正则表达式来查找匹配的模式之一,我们将其收集到列表中。


推荐阅读