java - 正则捕捉中(.*?)和(.*)的区别
伊谢尔伦
伊谢尔伦 2017-04-18 10:55:01
0
5
620

Java使用正则匹配捕捉
1 Pattern p = Pattern.compile("name="sign" value="(.*)"/>");
2 Pattern p = Pattern.compile("name="sign" value=*"(.?)**"/>");
第二个比第一个多了一个?号,请问其中区别是什么

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(5)
伊谢尔伦

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.

Peter_Zhu

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

洪涛

The former will stop after finding a match, while the latter will find all matching targets.

小葫芦

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

  1. 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
  1. 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
刘奇

?The smallest matching one will be selected.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template