Search code examples
scalaparboiled

Match {N,M} chars in Parboiled


How do I write a rule for

  • at least N chars - regex [a-z](2,}

  • at most N chars - regex [a-z](,5}

  • from N to M chars - regex [a-z]{3,10}

in Parboiled?


Solution

  • You might be looking for the times combinator. You can either use times with a single Int (meaning repeat the rule exactly n times) or with an (Int, Int) (meaning repeat the rule between n and m times). You can use times together with oneOrMore, zeroOrMore, ~, and ! for the desired effects:

    //Matches regex "a{n,}"
    rule {
         n.times("a") ~ zeroOrMore("a") //match on n "a"s followed by zero or more "a"s (so at least n "a"s)
    }
    
    //Matches regex "a{,m}"
    rule {
        !(m.times("a") ~ oneOrMore("a")) //do not match on m "a"s followed by one or more "a" (so at most m "a"s)
    }
    
    //Matches regex "a{n, m)"
    rule {
         (n to m).times("a") ~ EOI
    }