Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6704377
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T07:16:54+00:00 2026-05-26T07:16:54+00:00

Suppose I’m writing a rudimentary SQL parser in Scala. I have the following: class

  • 0

Suppose I’m writing a rudimentary SQL parser in Scala. I have the following:

class Arith extends RegexParsers {
    def selectstatement: Parser[Any] = selectclause ~ fromclause
    def selectclause: Parser[Any] = "(?i)SELECT".r ~ tokens
    def fromclause: Parser[Any] = "(?i)FROM".r ~ tokens
    def tokens: Parser[Any] = rep(token) //how to make this non-greedy?
    def token: Parser[Any] = "(\\s*)\\w+(\\s*)".r
}

When trying to match selectstatement against SELECT foo FROM bar, how do I prevent the selectclause from gobbling up the entire phrase due to the rep(token) in ~ tokens?

In other words, how do I specify non-greedy matching in Scala?

To clarify, I’m fully aware that I can use standard non-greedy syntax (*?) or (+?) within the String pattern itself, but I wondered if there’s a way to specify it at a higher level inside def tokens. For example, if I had defined token like this:

def token: Parser[Any] = stringliteral | numericliteral | columnname

Then how can I specify non-greedy matching for the rep(token) inside def tokens?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T07:16:54+00:00Added an answer on May 26, 2026 at 7:16 am

    Not easily, because a successful match is not retried. Consider, for example:

    object X extends RegexParsers {
      def p = ("a" | "aa" | "aaa" | "aaaa") ~ "ab"
    }
    
    scala> X.parseAll(X.p, "aaaab")
    res1: X.ParseResult[X.~[String,String]] = 
    [1.2] failure: `ab' expected but `a' found
    
    aaaab
     ^
    

    The first match was successful, in parser inside parenthesis, so it proceeded to the next one. That one failed, so p failed. If p was part of alternative matches, the alternative would be tried, so the trick is to produce something that can handle that sort of thing.

    Let’s say we have this:

    def nonGreedy[T](rep: => Parser[T], terminal: => Parser[T]) = Parser { in =>
      def recurse(in: Input, elems: List[T]): ParseResult[List[T] ~ T] =
        terminal(in) match {
          case Success(x, rest) => Success(new ~(elems.reverse, x), rest)
          case _ => 
            rep(in) match {
              case Success(x, rest) => recurse(rest, x :: elems)
              case ns: NoSuccess    => ns
            }
        }
    
      recurse(in, Nil)
    }  
    

    You can then use it like this:

    def p = nonGreedy("a", "ab")
    

    By the way,I always found that looking at how other things are defined is helpful in trying to come up with stuff like nonGreedy above. In particular, look at how rep1 is defined, and how it was changed to avoid re-evaluating its repetition parameter — the same thing would probably be useful on nonGreedy.

    Here’s a full solution, with a little change to avoid consuming the “terminal”.

    trait NonGreedy extends Parsers {
        def nonGreedy[T, U](rep: => Parser[T], terminal: => Parser[U]) = Parser { in =>
          def recurse(in: Input, elems: List[T]): ParseResult[List[T]] =
            terminal(in) match {
              case _: Success[_] => Success(elems.reverse, in)
              case _ => 
                rep(in) match {
                  case Success(x, rest) => recurse(rest, x :: elems)
                  case ns: NoSuccess    => 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)
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose I have this code: class Num: def __init__(self,num): self.n = num def getn(self):
Suppose you have the following object hierarchy: class Vehicle { public: virtual ~Vehicle() {}
Suppose i have the following class. public class Location { public Id { get;
Suppose you have the following Generic class heirarchy: public abstract class GenericBase<T> { T
Suppose, I have following classes: public class DisposableObj : IDisposable { public ChildObj CreateObj();
Suppose I have the following CSS rule in my page: body { font-family: Calibri,
Suppose I have a class module clsMyClass with an object as a member variable.
Suppose we have the Lyric model: class Lyric < ActiveRecord::Base belongs_to :song end and
Suppose I have a grid of squared defined like so in a class: Square
Suppose I have a innerclass extends asynctask called A and the outerclass extends Activity

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.