Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import scala.util.parsing.combinator.{ Parsers, RegexParsers }
import scala.util.parsing.input.{ CharSequenceReader, Reader }
object ParsingExample extends Parsers {
override type Elem = Char
object Delimiter extends Parser[String] {
def apply(reader: Input): ParseResult[String] = {
if (reader atEnd) {
Failure("end of string", reader)
} else if (reader.first != '-') {
Failure("no separator found", reader)
} else {
Success(reader.first, reader.rest)
}
}
}
val DigitSequence = Parser { reader =>
if (reader atEnd) {
Failure("end of string", reader)
} else if (!reader.first.isDigit) {
Failure("no digits found", reader)
} else {
var digits = reader.first.toString
var rest = reader.rest
while (!rest.atEnd && rest.first.isDigit) {
digits += rest.first
rest = rest.rest
}
Success(digits, rest)
}
}
case class RolodexCard(pre: String, post: String)
val PhoneNumber = DigitSequence ~ Delimiter ~ DigitSequence map {
case pre ~ _ ~ post => RolodexCard(pre, post)
}
}
object RegexParsingExample extends RegexParsers {
case class RolodexCard(pre: String, post: String)
val DigitSequence = """\d+""".r
val Delimiter = "-"
val PhoneNumber = DigitSequence ~ Delimiter ~ DigitSequence map {
case pre ~ _ ~ post => RolodexCard(pre, post)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment