Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Not easily, because a successful match is not retried. Consider, for example:</p> <pre><code>object X extends RegexParsers { def p = ("a" | "aa" | "aaa" | "aaaa") ~ "ab" } scala&gt; X.parseAll(X.p, "aaaab") res1: X.ParseResult[X.~[String,String]] = [1.2] failure: `ab' expected but `a' found aaaab ^ </code></pre> <p>The first match was successful, in parser inside parenthesis, so it proceeded to the next one. That one failed, so <code>p</code> failed. If <code>p</code> was part of alternative matches, the alternative would be tried, so the trick is to produce something that can handle that sort of thing.</p> <p>Let's say we have this:</p> <pre><code>def nonGreedy[T](rep: =&gt; Parser[T], terminal: =&gt; Parser[T]) = Parser { in =&gt; def recurse(in: Input, elems: List[T]): ParseResult[List[T] ~ T] = terminal(in) match { case Success(x, rest) =&gt; Success(new ~(elems.reverse, x), rest) case _ =&gt; rep(in) match { case Success(x, rest) =&gt; recurse(rest, x :: elems) case ns: NoSuccess =&gt; ns } } recurse(in, Nil) } </code></pre> <p>You can then use it like this:</p> <pre><code>def p = nonGreedy("a", "ab") </code></pre> <p>By the way,I always found that looking at how other things are defined is helpful in trying to come up with stuff like <code>nonGreedy</code> above. In particular, look at how <code>rep1</code> is defined, and how it was changed to avoid re-evaluating its repetition parameter -- the same thing would probably be useful on <code>nonGreedy</code>.</p> <p>Here's a full solution, with a little change to avoid consuming the "terminal".</p> <pre><code>trait NonGreedy extends Parsers { def nonGreedy[T, U](rep: =&gt; Parser[T], terminal: =&gt; Parser[U]) = Parser { in =&gt; def recurse(in: Input, elems: List[T]): ParseResult[List[T]] = terminal(in) match { case _: Success[_] =&gt; Success(elems.reverse, in) case _ =&gt; rep(in) match { case Success(x, rest) =&gt; recurse(rest, x :: elems) case ns: NoSuccess =&gt; ns } } recurse(in, Nil) } } class Arith extends RegexParsers with NonGreedy { // Just to avoid recompiling the pattern each time val select: Parser[String] = "(?i)SELECT".r val from: Parser[String] = "(?i)FROM".r val token: Parser[String] = "(\\s*)\\w+(\\s*)".r val eof: Parser[String] = """\z""".r def selectstatement: Parser[Any] = selectclause(from) ~ fromclause(eof) def selectclause(terminal: Parser[Any]): Parser[Any] = select ~ tokens(terminal) def fromclause(terminal: Parser[Any]): Parser[Any] = from ~ tokens(terminal) def tokens(terminal: Parser[Any]): Parser[Any] = nonGreedy(token, terminal) } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload