从全文中检索字符串的一部分

我有一个字符串变量,其中包含一个文本以及其中的一些日期。现在我想从文本中检索日期。我该怎么做。

String a ="I am ready at time -S 2019-06-16:00:00:00 and be there"

现在我想2019-06-16:00:00:00从那里取回。日期格式将始终采用相同的格式,但我只需要从文本中检索日期。


临摹微笑
浏览 109回答 4
4回答

江户川乱折腾

尝试使用带有模式的正则表达式匹配器:\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));}

噜噜哒

使用正则表达式从文本中检索日期。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());    }}

弑天下

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()) {&nbsp; &nbsp; System.out.println(matcher.group("date"));&nbsp; // 2019-06-16&nbsp; &nbsp; System.out.println(matcher.group("time"));&nbsp; // 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) {&nbsp; &nbsp; String a = "I am ready at time -S 2019-06-16:00:00:00 and be there"&nbsp; &nbsp; // create matcher for pattern p and given string&nbsp; &nbsp; Matcher m = p.matcher(a);&nbsp; &nbsp; // if an occurrence if a pattern was found in the given string...&nbsp; &nbsp; if (m.find()) {&nbsp; &nbsp; &nbsp; &nbsp; // ...then you can use group() methods.&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(m.group(0));&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java