我尝试从字符串中提取错误号,例如"Wrong parameters - Error 1356"
:
Pattern p = Pattern.compile("(\\d*)");
Matcher m = p.matcher(myString);
m.find();
System.out.println(m.group(1));
这不会打印任何内容,这对我来说很奇怪,因为*
means * - Matches the preceding element zero or more times
from Wiki http://en.wikipedia.org/wiki/Regular_expression
我也去了www.regexr.com http://www.regexr.com/ and 正则表达式101.com http://regex101.com/并测试它,结果是相同的,这个表达式没有任何内容\d*
然后我开始测试一些不同的东西(所有测试都是在我提到的网站上进行的):
-
(\d)*
不起作用
-
\d{0,}
不起作用
-
[\d]*
不起作用
-
[0-9]*
不起作用
-
\d{4}
works
-
\d+
works
-
(\d+)
works
-
[0-9]+
works
因此,我开始在网上搜索是否可以找到对此的解释。我能找到的最好的是here http://www.rexegg.com/regex-greed.html在量词部分,其中指出:
\d? Optional digit (one or none).
\d* Eat as many digits as possible (but none if necessary)
\d+ Eat as many digits as possible, but at least one.
\d*? Eat as few digits as necessary (possibly none) to return a match.
\d+? Eat as few digits as necessary (but at least one) to return a match.
问题
由于英语不是我的主要语言,我很难理解其中的区别(主要是(but none if necessary)
部分)。那么正则表达式专家们能用简单的话解释一下吗?
我在这里发现的与这个问题最接近的事情是这个:正则表达式:星号重复运算符的所有格量词,即 \d** https://stackoverflow.com/questions/16192672/regex-possessive-quantifier-for-the-star-repetition-operator-i-e-d但这里没有解释其中的区别。