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?

2
  • 2
    What have you coded so far? Commented Sep 12, 2015 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? Commented Sep 13, 2015 at 0:37

2 Answers 2

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 ~.

Sign up to request clarification or add additional context in comments.

Comments

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)
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.