The greedy pattern and non-greedy pattern of regular expression knowledge explanation (Java version example) __ Regular expressions

Source: Internet
Author: User

Regular expression knowledge of the series, through the code example to illustrate the regular expression of knowledge, suggest that you follow the example hand to play again.

The source code download address for this example: http://download.csdn.net/detail/gnail_oug/9504094


Example:

1, greedy mode to extract the content of HTML tags

2, non-greedy mode in advance the content of HTML tags

Extract content from TD elements
String str= "<table><tr><td>hello World</td><td>hello regex</td ></tr></table> ";

Greedy Mode  * + {n,} The default is greedy pattern matching
System.out.println ("= = Greedy mode =====");
Compiles regular expressions to schema objects pattern
p=pattern.compile ("<td>.*</td>");
Get the matching device
Matcher m=p.matcher (str);
Finds a match through the Find method, returns true if found, otherwise returns false while
(M.find ()) {
	//Gets the substring found in the previous find lookup by the group method, start, The end method gets the beginning and ending position of the substring
	System.out.println (m.group () + "   position: [" +m.start () + "," +m.end () + "]");
}

Non-greedy mode,? followed by * + {n,}, and so on, to express the non-greedy mode, notice and the sub-expression after the partition, subexpression after the expression matching 0 or 1 times
System.out.println ("= = not greedy mode =====");
P=pattern.compile ("<td>.*?</td>");
M=p.matcher (str);
while (M.find ()) {
	System.out.println (M.group () + "   position: [" +m.start () + "," +m.end () + "]);
}

Run Result:

= = Greedy mode =====
<td>hello world</td><td>hello regex</td>   position: [11,51]
= = Not greedy mode = = = =
<td>hello world</td>   position: [11,31]
<td>hello regex</td>   location: [31,51]












Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.