基本例子
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
println(SimpleParser.parseAlice)
//Fails to find a match
println(SimpleParser.parseBarb)
输出如下:
[1.6] parsed: Alice
res0: Unit = ()
[1.1] failure: string matching regex `[A-Z][a-z]+' expected but `b' found
barb went Upside Down.
^
Alice
示例中的 [1.6]
表示匹配的开始位于 1
的位置,并且匹配的第一个字符在位置 6
处开始。