从Java中的字符串中提取多个日期(dd-MMM-yyyy格式) [英] Extract multiple dates (dd-MMM-yyyy format) from a string in java
问题描述
我在所有地方都进行了搜索,但是找不到具体的解决方案,文档也没有对此进行介绍.所以我想从此字符串"2019年3月1日至2019年3月31日"
中提取开始日期和结束日期.问题是我无法同时提取两个日期字符串.
我在这里找到了最接近的解决方案,但由于声誉低下,无法发表评论询问如何分别提取值: https://stackoverflow.com/a/8116229/10735227
我正在使用正则表达式模式查找出现的内容,并首先将两个出现的内容都提取到2个字符串中.
这是我尝试过的:
模式p = Pattern.compile((\\ d {1,2}-[a-zA-Z] {3}-\\ d {4})");;匹配器m = p.matcher(str);while(m.find()){startdt = m.group(1);enddt = m.group(1);//我认为这是错误的,不知道如何解决}System.out.println("startdt:" + startdt +"enddt:" + enddt);
输出为:
startdt:31-Mar-2019 enddt:31-Mar-2019
另外,我需要使用DateFormatter将该字符串转换为日期(如果需要,可以在一位数字的日期前添加结尾的0).
您只需两次调用 find
方法就可以捕获两个日期,如果只有一个,则只能捕获第一个:
String str ="2019年3月1日至2019年3月31日";字符串startdt = null,enddt = null;模式p = Pattern.compile((\\ d {1,2}-[a-zA-Z] {3}-\\ d {4})");匹配器m = p.matcher(str);if(m.find()){startdt = m.group(1);if(m.find()){enddt = m.group(1);}}System.out.println("startdt:" + startdt +"enddt:" + enddt);
请注意,这可以与 while(m.find())
和 List< String
一起使用,以便提取您可以找到的每个日期./p>
I have searched everywhere for this but couldn't get a specific solution, and the documentation also didn't cover this. So I want to extract the start date and end date from this string "1-Mar-2019 to 31-Mar-2019"
. The problem is I'm not able to extract both the date strings.
I found the closest solution here but couldn't post a comment asking how to extract values individually due to low reputation: https://stackoverflow.com/a/8116229/10735227
I'm using a regex pattern to look for the occurrences and to extract both occurrences to 2 strings first.
Here's what I tried:
Pattern p = Pattern.compile("(\\d{1,2}-[a-zA-Z]{3}-\\d{4})");
Matcher m = p.matcher(str);
while(m.find())
{
startdt = m.group(1);
enddt = m.group(1); //I think this is wrong, don't know how to fix it
}
System.out.println("startdt: "+startdt+" enddt: "+enddt);
Output is:
startdt: 31-Mar-2019 enddt: 31-Mar-2019
Additionally I need to use DateFormatter to convert the string to date (adding the trailing 0 before single digit date if required).
You can catch both dates simply calling the find
method twice, if you only have one, this would only capture the first one :
String str = "1-Mar-2019 to 31-Mar-2019";
String startdt = null, enddt = null;
Pattern p = Pattern.compile("(\\d{1,2}-[a-zA-Z]{3}-\\d{4})");
Matcher m = p.matcher(str);
if(m.find()) {
startdt = m.group(1);
if(m.find()) {
enddt = m.group(1);
}
}
System.out.println("startdt: "+startdt+" enddt: "+enddt);
Note that this could be used with a while(m.find())
and a List<String
to be able to extract every date your could find.
这篇关于从Java中的字符串中提取多个日期(dd-MMM-yyyy格式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!