简体   繁体   English

Scala / Java-解析只有日期部分的字符串

[英]Scala/Java - Parsing the String which only has date part

So I have 2 strings 所以我有2弦

val a : String = "foo April 06 1994 bar"
val b : String = "April 06 1994" // this format can change

and I have a seq of 4 parsers 我有4个解析器

private val dateParsers = Seq(
    JChronicDateParser,
    UKDateParser,
    USDateParser,
    GermanDateParser
  )

and now I parse them variables I get succesful results in both cases 现在我解析它们的变量在两种情况下我都获得成功的结果

dateParsers.map(parsers => {
            parsers.parse(variable)//a or b
          })

Is there any efficient way to fail the parsing of the string a , I want parsers to fail when there's any extra info or characters in the string with the date part? 有什么有效的方法可以使string a的解析失败,当字符串中包含日期部分的任何额外的信息或字符时,我希望解析器失败?

I have tried methods like not using any parser rather getting the string in and formatting it with 我已经尝试过一些方法,例如不使用任何解析器,而是获取字符串并将其格式化

val dateFormat = new SimpleDateFormat("yyyy-MM-dd")
dateFormat.parse(a) // it fails in both cases so no good

Your SimpleDateFormat fails because the format you give it is wrong. 您的SimpleDateFormat失败,因为您输入的格式错误。 Try "MMMM dd yyyy" . 尝试"MMMM dd yyyy"

Also, SimpleDateFormat isn't a very good option. 另外, SimpleDateFormat也不是一个很好的选择。 Since java 8, it's better to use DateTimeFormatter instead: 从Java 8开始,最好改用DateTimeFormatter

DateTimeFormatter.ofPattern("MMMM dd yyyy").parse("April 06 1994")

As to your other question - "Is there any efficient way to fail the parsing of the string a" - I have no idea what you are asking ... Throw exception? 至于您的另一个问题-“是否有任何有效的方法来使字符串a的解析失败”-我不知道您在问什么...引发异常? Return an Option ? 返回Option a Try ? 一个Try

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM