尝试使用带有模式的正则表达式匹配器:\d{4}-\d{2}-\d{2}:\d{2}:\d{2}:\d{2}示例代码:String a = "I am ready at time -S 2019-06-16:00:00:00 and be there";String pattern = "\\d{4}-\\d{2}-\\d{2}:\\d{2}:\\d{2}:\\d{2}";Pattern r = Pattern.compile(pattern);Matcher m = r.matcher(a);while (m.find()) { System.out.println("found a timestamp: " + m.group(0));}
String str = "I am ready at time -S 2019-06-16:00:00:00 and be there";Pattern pattern = Pattern.compile("(?<date>\\d{4}-\\d{2}-\\d{2}):(?<time>\\d{2}:\\d{2}:\\d{2})");Matcher matcher = pattern.matcher(str);if(matcher.matches()) { System.out.println(matcher.group("date")); // 2019-06-16 System.out.println(matcher.group("time")); // 00:00:00}
我建议为此使用正则表达式,如下所示:private static final Pattern p = Pattern.compile("(\d{4}-\d{2}-\d{2}:\d{2}:\d{2}:\d{2})");public static void main(String[] args) { String a = "I am ready at time -S 2019-06-16:00:00:00 and be there" // create matcher for pattern p and given string Matcher m = p.matcher(a); // if an occurrence if a pattern was found in the given string... if (m.find()) { // ...then you can use group() methods. System.out.println(m.group(0)); }}