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]