Java使用正则匹配捕捉
1 Pattern p = Pattern.compile("name="sign" value="(.*)"/>");
2 Pattern p = Pattern.compile("name="sign" value=*"(.?)**"/>");
第二个比第一个多了一个?号,请问其中区别是什么
伊谢尔伦2017-04-18 10:57:01
The difference between greedy and non-greedy.
To put it simply, non-greedy means that it will stop when it matches, regardless of whether there is another match later, while greedy means that it will not stop as long as there is still a match later.
天蓬老师2017-04-18 10:57:01
When a regular expression contains qualifiers that accept repetitions, the usual behavior is to match as many characters as possible (while the entire expression can be matched). Take this expression as an example: a.*b, it will match the longest string starting with a and ending with b. If you use it to search for aabab, it will match the entire string aabab. This is called greedy matching.
Sometimes, we need lazy matching, that is, matching as few characters as possible. The qualifiers given above can be converted into lazy matching patterns by appending a question mark ? after them. In this way, .*? means matching any number of repetitions, but using the fewest repetitions that will make the overall match successful. Now look at the lazy version of the example:
a.*?b matches the shortest string starting with a and ending with b. If you apply it to aabab, it will match aab (characters 1 to 3) and ab (characters 4 to 5).
Copied from: http://deerchao.net/tutorials... 30-minute introduction to regular expressions, greedy and lazy part
PHP中文网2017-04-18 10:57:01
The former will stop after finding a match, while the latter will find all matching targets.
高洛峰2017-04-18 10:57:01
This question involves greedy mode and lazy mode (also called non-greedy mode) in regular expressions
First, let’s take a look at the definitions of these two
Greedy mode and maximum matching*
,+
,'{n,}',.*
are both greedy modes. The so-called maximum matching, let me give you an example
var pattern = /a.*e/
console.log("abcd fsdfsdfsesfdfsdfsesdfedfsdfses".match(pattern)); //结果为abcd fsdfsdfsesfdfsdfsesdfedfsdfse
Lazy mode, on the premise of successful matching, match as few times as possible.
Still the above example:
var pattern = /a.*?e/
console.log("abcd fsdfsdfsesfdfsdfsesdfedfsdfses".match(pattern)); //结果为abcd fsdfsdfse