4 回答

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超5個(gè)贊
嘗試使用帶有模式的正則表達(dá)式匹配器:
\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貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊
使用正則表達(dá)式從文本中檢索日期。
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貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
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貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
我建議為此使用正則表達(dá)式,如下所示:
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));
}
}
添加回答
舉報(bào)