简体   繁体   中英

Scala parsing string sequence

I wish to parse a sequence of string into individual tokens. Right now it only parses the first word.

class SimpleRegexParser extends RegexParsers{

 def word: Parser[String]    = """[a-z]+""".r ^^ { _.toString }

}

object SimpleRegexParserMain extends SimpleRegexParser{
 def main(args: Array[String]) = {
println(parse(word, "johnny has a little lamb"))

 }
}

Right now I am getting : [1.7] parsed: johnny

How can I parse the whole string into individual tokens, so that this works for variable string length.

Any pointers to make this work are welcome. Please tell me how I can make it work in scala.

Okay. I found the answer to this.

I had to change the definition of word.

Here is the updated definition:

class SimpleRegexParser extends RegexParsers{

def word: Parser[String]    = rep("""[a-z]+""".r) ^^ { _.toString }

}

Previous expression was working for single word, I now have a repetition of word rep() .

Here is the result:

[1.25] parsed: List(johnny, has, a, little, lamb)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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