Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

regex - How to extract a date from a string and put it into a date variable in Java

I have been looking around stack-overflow and various other websites for the solution to my problem but haven't found any suitable for my specific purposes and have been unable to change these solutions to suit my code. These include regex codes which I do not fully understand or know how to manipulate.

So here is my question, I have a string which has a structure:

"name+" at:"+Date+" Notes:"+meetingnotes"

(name, Date and meetingnotes being variables). What I want to do is extract the date part of the string and stick it in a Date variable. The basic Dateformat for the dates is "yyyy-MM-dd". How do I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For this, a regular expression is your friend:

String input = "John Doe at:2016-01-16 Notes:This is a test";

String regex = " at:(\d{4}-\d{2}-\d{2}) Notes:";
Matcher m = Pattern.compile(regex).matcher(input);
if (m.find()) {
    Date date = new SimpleDateFormat("yyyy-MM-dd").parse(m.group(1));
    // Use date here
} else {
    // Bad input
}

Or in Java 8+:

    LocalDate date = LocalDate.parse(m.group(1));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...