scala - 如何使用 SBT 解析器匹配由可选空格包围的字符串

标签 scala parsing sbt

我正在尝试使用 SBT 解析器 ( http://www.scala-sbt.org/0.13/docs/Parsing-Input.html ) 解析 sbt InputTask 的命令行参数,但我无法编写解析器来匹配以下伪正则表达式:

\w+(-n|--dry-run)\w+

这是我能想到的最明智的表达方式。如果输入字符串匹配,此处的结果应为 Some(true)

import sbt.complete.Parser
import sbt.complete.DefaultParsers._

val dryRunOptions: Parser[String] = OptSpace ~> ("-n" | "--dry-run") <~ OptSpace
val dryRunParser: Parser[Boolean] = flag(dryRunOptions)

Parser(dryRunParser)("-n").result
Parser(dryRunParser)(" -n").result
Parser(dryRunParser)("-n ").result
Parser(dryRunParser)(" -n ").result

Parser(dryRunParser)("--dry-run").result
Parser(dryRunParser)(" --dry-run").result
Parser(dryRunParser)("--dry-run ").result
Parser(dryRunParser)(" --dry-run ").result

不幸的是,这与任何这些情况都不匹配!

res0: Option[Boolean] = None
res1: Option[Boolean] = None
res2: Option[Boolean] = None
res3: Option[Boolean] = None

res4: Option[Boolean] = None
res5: Option[Boolean] = None
res6: Option[Boolean] = None
res7: Option[Boolean] = None

我可以让它匹配几个案例,但不能匹配所有案例。任何帮助表示赞赏!

最佳答案

您正在以错误的方式检查解析器的正确性。在这种情况下,您应该使用 .resultEmpty.isValid 而不是 .result,如 tests here 中所示。 。然后你的代码就可以正常工作了:

import sbt.complete.Parser
import sbt.complete.DefaultParsers._

val dryRunOptions: Parser[String] = OptSpace ~> ("-n" | "--dry-run") <~ OptSpace
val dryRunParser: Parser[Boolean] = flag(dryRunOptions)

val test = Seq("-n", " -n", "-n ", " -n   ",
  "--dry-run", " --dry-run", "--dry-run ", " --dry-run   ")

test.foldLeft(true)((b:Boolean, input:String) =>
  b && Parser(dryRunParser)(input).resultEmpty.isValid)

结果:

res0: Boolean = true

关于scala - 如何使用 SBT 解析器匹配由可选空格包围的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39899699/

相关文章:

scala - 无法将 unicode 符号转换为西里尔字母

scala - .with在scala中的替代方法

string - 在 UNIX 上解析文件中的数字

scala - 如何依赖 GitHub 中的 PlayProject?

scala - 将输入任务与 sbt 中的动态任务相结合

scala - uPickle 和 ScalaJS : sealed trait serialisation

python - 如何提高 Spark 中的小数精度?

c++ - Boost Spirit x3条件(三元)运算符解析器(后续问题)

parsing - 如何有效利用Alex的起始码功能?

scala - 如何在 play 框架和 build.sbt 中获取应用程序版本