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

我的梦境 提交于 2020-02-26 04:18:07

问题


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"?


回答1:


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.



来源:https://stackoverflow.com/questions/22079519/why-isnt-the-x-at-most-n-times-regex-quantifier-included-in-java-in-the-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!