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

时间:2019-05-31 07:09:27

标签: java java-8

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

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

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

4 个答案:

答案 0 :(得分:3)

尝试将正则表达式匹配器用于以下模式:

\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));
}

答案 1 :(得分:0)

我建议为此使用正则表达式,例如:

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));
    }
}

答案 2 :(得分: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
}

答案 3 :(得分: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());
    }
}