-1

Java docs tell us you can have this greedy quantifiers:

X{n}    X, exactly n times
X{n,}   X, at least n times
X{n,m}  X, at least n but not more than m times

There is no mention of having X, at MOST n times.


So I made a little test:

boolean atMost = Pattern.matches("X{,3}", "XX");

I expected atMost to be true, since it's safe to assume the lower bound to be zero. Instead, I got an exception:

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 0
X{,3}
^

Note it's not a thing of being Greedy, Reluctant or Possessive: "X{,3}?" and "X{,3}+" also don't work.

I could have used "X{0,3}" to achieve the pattern I'm looking for, but that's not my question.


Why isn't the X, at MOST n times regex quantifier included in Java, in the X{,n} syntax?

How is it like in other programming languages or regex "flavors"?

orlandocr
  • 313
  • 2
  • 8
  • 7
    Because a "3 at most" quantifier `{,3}` is *exactly the same* as "between zero and three: `{0,3}`. I think it's simple as that. – aliteralmind Feb 27 '14 at 20:25
  • I'd say because at most is finite and at least is not. It would be silly to put `"X{3,Double.POSITIVE_INFINITY}"` :) – C.B. Feb 27 '14 at 20:25
  • @aliteralmind As I mentioned in the question, I'm aware of that. It's not a question of finding a matching regex, but a question on WHY wasn't `{,3}` included. – orlandocr Feb 27 '14 at 20:28
  • 2
    @orlandocr: aliteralmind is saying that syntax wasn't provided because it only costs 1 character to do it without that syntax, and the savings of 1 character weren't considered worth it. – Louis Wasserman Feb 27 '14 at 20:29
  • @C.B. Could you expand a little? I don't get it, so what if "at most" is finite? – orlandocr Feb 27 '14 at 20:31
  • 1
    This is a general aspect of regex, not just Java's regex engine. – CAustin Feb 27 '14 at 20:31
  • On a side note, it amazed me `boolean exactly = Pattern.matches("X{9999995465468484864312156464897946854564684654648646849645878789798789798787987846543}", "XXX");` is `false`, there was no Exception. – orlandocr Feb 27 '14 at 20:31
  • 1
    @orlandocr Essentially I am saying *only* looking the notation `{3,}` Implies from `3` to `Infinity`, so shouldn't `{,3}` Imply from `-Infinity` to `3`? BTW, I am aware matching negative values would be senseless. – C.B. Feb 27 '14 at 20:34

1 Answers1

3

Its not a {n,m} issue, its a PARSING issue.

Left to right, { + number is all that has to be validated for a possible range
quantifier, otherwise { is literal and the parse continues.

Also, the paser wants a simple number available as the range start to compare with the
range end. It doesn't want to dither/allow simultaneous {min_default,max_default} or {,}

It would be too complicated at that low level to allow both.