How do you match a string surrounded by optional spaces with SBT Parsers

I am trying to parse the command line argument for sbt InputTask using SBT Parsers ( http://www.scala-sbt.org/0.13/docs/Parsing-Input.html ), but I cannot write a parser to match the following pseudo- regular expression:

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

Here is the most reasonable way to express this that I can think of. The results should be here Some(true)if the input line matches.

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

Unfortunately, this does not correspond to any of these cases!

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

I can get this to fit multiple cases with multiple options on this, but never all of them. Any help appreciated!

+4
1

. , .resultEmpty.isValid .result, , . , :

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
0

Source: https://habr.com/ru/post/1656952/


All Articles