问题描述
我尝试从诸如 "Wrong parameters - Error 1356"
之类的字符串中提取错误编号:
I try to extract the error number from strings like "Wrong parameters - Error 1356"
:
Pattern p = Pattern.compile("(\\d*)");
Matcher m = p.matcher(myString);
m.find();
System.out.println(m.group(1));
这不会打印任何内容,这对我来说很奇怪,因为 *
的意思是 * - 匹配
And this does not print anything, that became strange for me as the *
means * - Matches the preceding element zero or more times
from Wiki
我还访问了 www.regexr.com 和 regex101.com 并测试它,结果是一样的,这个表达式没有什么\d*
I also went to the www.regexr.com and regex101.com and test it and the result was the same, nothing for this expression \d*
然后我开始测试一些不同的东西(所有测试都是在我提到的网站上进行的):
Then I start to test some different things (all tests made on the sites I mentioned):
(\d)*
不起作用\d{0,}
不起作用[\d]*
不起作用[0-9]*
不起作用\d{4}
有效\d+
有效(\d+)
有效[0-9]+
有效
(\d)*
doesn't work\d{0,}
doesn't work[\d]*
doesn't work[0-9]*
doesn't work\d{4}
works\d+
works(\d+)
works[0-9]+
works
所以,如果我能找到对此的解释,我就开始在网上搜索.我能找到的最好的是量词部分的此处,其中指出:
So, I start to search on the web if I could find an explanation for this. The best I could find was here on the Quantifier section, which states:
\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.
问题
由于英语不是我的主要语言,我无法理解其中的区别(主要是 (但没有必要)
部分).那么,您能用简单的话解释一下这个正则表达式专家吗?
As english is not my primary language I'm having trouble to understand the difference (mainly the (but none if necessary)
part). So could you Regex expert guys explain this in simple words please?
我在 SO 上找到的最接近这个问题的是这个:Regex:星形重复运算符的所有格量词,即 \d** 但这里不解释区别.
The closest thing that I find to this question here on SO was this one: Regex: possessive quantifier for the star repetition operator, i.e. \d** but here it is not explained the difference.
推荐答案
*
量词匹配零个或多个出现.
实际上,这意味着
\d*
将匹配所有可能的输入,包括空字符串.因此,您的正则表达式匹配输入字符串的开头并返回空字符串.
will match every possible input, including the empty string. So your regex matches at the start of the input string and returns the empty string.
这篇关于正则表达式量词 plus 和 star 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!