Questions And Answers

More Tutorials

Scala Parser Combinators


Basic Example

import scala.util.parsing.combinator._
class SimpleParser extends RegexParsers {
 // Define a grammar rule, turn it into a regex, and apply it the input.
 def word: Parser[String] = """[A-Z][a-z]+""".r ^^ { _.toString }
object SimpleParser extends SimpleParser {
 val parseAlice = parse(word, "Alice went to Alamo Square.")
 val parseBarb = parse(word, "barb went Upside Down.")
//Successfully finds a match
//Fails to find a match

The output will be as follows:

[1.6] parsed: Alice
res0: Unit = ()
[1.1] failure: string matching regex `[A-Z][a-z]+' expected but `b' found
barb went Upside Down.

[1.6] in the Alice example indicates that the start of the match is at position 1, and the fist character remaining to match starts at position 6.


In this page (written and validated by ) you learned about Scala Parser Combinators . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala Partial Functions.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.