gpt4 book ai didi

java - 从字符串中提取日期

转载 作者:行者123 更新时间:2023-12-02 05:34:20 25 4
gpt4 key购买 nike

我想从java字符串中查找日期。但我无法做到这一点,请帮忙

String : 01-02-2014 <2>
Ineed output like :01-02-2014

我的代码:

public String rejex(String idate){
String result = null;
try{
String regex = "([1-9]|[012][0-9]|3[01])[-/]\\s*(0[1-9]|1[012])[-/]\\s*((19|20)?[0-9]{2})";
result = idate.replaceAll(regex, "$1-$2-$3");
}catch(Exception e){}
return result;

}

最佳答案

您正在用它们本身替换您所追求的内容(日期段)。

如果你想提取它,这将起作用:

    String regex = "(([1-9]|[012][0-9]|3[01])[-/]\\s*(0[1-9]|1[012])[-/]\\s*((19|20)?[0-9]{2})).*?<(\\d+)>";
String str = "This is a random string 01-02-2014 <123> this is another part of that random string";

Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while(m.find())
{
System.out.println("Date: " + m.group(1));
System.out.println("Number: " + m.group(6));
}

产量:

Date: 01-02-2014
Number: 123

关于java - 从字符串中提取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25160787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com