2

I need to write a parser that can extract all the text between two parentheses:

parser("left-text ( text-to-extract ) right-text") = "text-to-extract"

The text-to-extract may contain parentheses, while both left-text and right-text cannot.

I'm using Scala parser combinators, and I would like the solution to fit into it. Can you help me?

Aslan986
  • 9,984
  • 11
  • 44
  • 75
  • 2
    What have you coded so far? –  Sep 12 '15 at 15:09
  • Do you really need _only_ the middle text (i.e., you'll throw away the left and right text), or are you just trying to split the string into these three pieces? – DaoWen Sep 13 '15 at 00:37

2 Answers2

1

If left text is { and right text is } then your parser should be the following.

def parser: Parser[String] = "{" ~> "[^}]*".r <~ "}"

The trick is to use ~> and <~instead of ~.

radumanolescu
  • 4,059
  • 2
  • 31
  • 44
jseteny
  • 412
  • 1
  • 6
  • 10
0

Expanding on @jseteny 's answer, here is a full example, using Scala 2.13.9

import scala.util.parsing.combinator.RegexParsers

class DemoParser extends RegexParsers {
  def removeBraces: Parser[String] = "{" ~> "[^}]*".r <~ "}"
}
object ExtractNested {
  def main(args: Array[String]): Unit = {
    val parser = new DemoParser
    val result = parser.parseAll(parser.removeBraces, "{text-to-extract}")
    println(result.get)
  }
}
radumanolescu
  • 4,059
  • 2
  • 31
  • 44