perc
perc

Reputation: 41

scala repsep with new non empty line separator

I've got 3 lines for parsing

John Smith
Nick Jackson
Liza Ashwood

i want to use repsep scala function with new line separator like this:

def parseLines: Parser[Map[String, String]] = repsep(parse, lineSeparator)

where lineSeparator is just "\n"

but sometimes there can be an empty lines without any names, just empty lines. in this case, i want to ignore this function

i was trying to use opt(repsep) which seems logical but this doesn't work

what can i do here? thx

Upvotes: 0

Views: 380

Answers (1)

Alexis C.
Alexis C.

Reputation: 93842

By empty lines, I'm assuming you can have data like this:

John Smith
            <-- empty line
Nick Jackson
Liza Ashwood

In this case, it means that there's two times the lineSeparator. So you can use the rep1 combinator to tell that there should be at least 1 but there can be more line separators between each line of data:

def parseLines: Parser[Map[String, String]] = repsep(line, rep1("\n")) ^^ (ListMap() ++_ )

For example:

object MyParser extends RegexParsers {

  override def skipWhitespace = false

  def parse(input: java.io.Reader) = parse(parseLines, input) match {
    case Success(res, _) => res
    case e => throw new RuntimeException(e.toString)
  }

  def parseLines: Parser[Map[String, String]] = repsep(line, rep1("\n")) ^^ (ListMap() ++_ )

  def oneOrMoreletters = "[a-zA-Z]+".r
  def line:Parser[(String, String)] = (oneOrMoreletters <~ " ") ~ oneOrMoreletters ^^ (t => (t._1, t._2))

}

Upvotes: 1

Related Questions