4 回答
TA贡献1851条经验 获得超5个赞
尝试使用带有模式的正则表达式匹配器:
\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));
}
TA贡献1784条经验 获得超7个赞
使用正则表达式从文本中检索日期。
public static void main(String[] args) {
String a = "I am ready at time -S 2019-06-16:00:00:00 and be there";
Pattern pattern = Pattern.compile("[0-9]{4}[-][0-9]{1,2}[-][0-9]{1,2}[:][0-9]{1,2}[:][0-9]{1,2}[:][0-9]{1,2}");
Matcher matcher = pattern.matcher(a);
while(matcher.find()){
System.out.println(matcher.group());
}
}
TA贡献1818条经验 获得超8个赞
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
}
TA贡献1865条经验 获得超7个赞
我建议为此使用正则表达式,如下所示:
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));
}
}
添加回答
举报