How to specify the presence or non-presence of white space in scala parser combinators?

StackOverflow https://stackoverflow.com/questions/21887505

  •  13-10-2022
  •  | 
  •  

سؤال

Let's say I have the following:

case class Var(s: String)

class MyParser extends JavaTokensParser {

  def variableExpr = "?" ~ identifier ^^ { case "?" ~ id => Var(id) }

  def identifier = //...

}

I want this to accept inputs of the form ?X but not ? X (with a space in between). How would this be expressed?

Thanks!

هل كانت مفيدة؟

المحلول

JavaTokensParser by default allows white spaces between any parsers. You could change this behavior this way:

override def skipWhitespace = false

Now you have to specify all white spaces manually:

def ws: Parser[Seq[Char]] = rep(' ')

def variableExpr = ws ~> "?" ~ identifier ^^ { case "?" ~ id => Var(id) }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top