开发者

Extracting a Date from "the meeting is on 12-DEC-2009 at 13:00" with Groovy

开发者 https://www.devze.com 2022-12-14 07:59 出处:网络
As the title states I have a string similar to: \"lorem ispom 12-DEC-2009 fsasdfsd 开发者_如何学Go12:00\"

As the title states I have a string similar to:

"lorem ispom 12-DEC-2009 fsasdfsd 开发者_如何学Go12:00"

OR

"the meeting is on 12-DEC-2009 at 13:00"

And I need to extract a Date with time from this.

What is an elegant and robust way of doing this in Groovy


I'd use a regex and the groovy "find" addition to the String class for this. Here's a simple regex that'll work for your test case. It could need to be tweaked depending on how lax you need to be on the input string.

import java.text.SimpleDateFormat

def extractDate(s) {
    s.find(/(\d\d-[A-Z]{3}-\d{4}).*(\d\d:\d\d)/) { full, date, time -> 
        return new SimpleDateFormat("dd-MMM-yyyy HH:mm").parse("$date $time")
    }
}
println extractDate("lorem ispom 12-DEC-2009 fsasdfsd 12:00")
println extractDate("the meeting is on 12-DEC-2009 at 13:00")

prints:

Sat Dec 12 12:00:00 CST 2009
Sat Dec 12 13:00:00 CST 2009
0

精彩评论

暂无评论...
验证码 换一张
取 消