为什么不是"MOST N次,X次"? Java中的"X {,n}"中包含的正则表达式量词句法? [英] Why isn't the "X, at MOST n times" regex quantifier included in Java, in the "X{,n}" syntax?
问题描述
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
没有提及拥有X, at MOST n times
.
所以我做了一点测试:
boolean atMost = Pattern.matches("X{,3}", "XX");
我希望atMost
为true
,因为可以安全地将下限假定为零.
相反,我遇到了一个例外:
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}
^
请注意,这不是贪婪,不情愿或可能的事情:"X{,3}?"
和"X{,3}+"
也不起作用.
Note it's not a thing of being Greedy, Reluctant or Possessive: "X{,3}?"
and "X{,3}+"
also don't work.
我本可以使用"X{0,3}"
来实现所需的模式,但这不是我的问题.
I could have used "X{0,3}"
to achieve the pattern I'm looking for, but that's not my question.
为什么X{,n}
语法中的Java不包含X, at MOST n times
regex量词?
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"?
推荐答案
它不是{n,m}问题,而是 PARSING 问题.
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.
此外,paser还希望有一个简单的数字,因为范围开始与
进行比较
范围结束.它不想同时抖动/允许{min_default,max_default}或{,}
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.
这篇关于为什么不是"MOST N次,X次"? Java中的"X {,n}"中包含的正则表达式量词句法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!