在Parboiled中匹配{N,M}个字符

时间:2015-04-08 21:48:16

标签: scala parboiled

如何为

编写规则
  • 至少N个字符 - 正则表达式[a-z](2,}

  • 最多N个字符 - 正则表达式[a-z](,5}

  • 从N到M字符 - 正则表达式[a-z] {3,10}

在Parboiled?

1 个答案:

答案 0 :(得分:2)

您可能正在寻找times组合子。您可以将timesInt一起使用(意味着重复规则n次)或使用(Int, Int)(意味着重复n之间的规则m次。您可以将timesoneOrMorezeroOrMore~!一起使用,以获得所需的效果:

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