Before doing the program to see the regular expression of greed and non-greedy mode, today, when the use of the time to remember, and now here to summarize, in case of their future use to pay attention to.
1. What is the greedy and non-greedy matching of regular expressions
such as: String str= "ABCAXC";
Patter p= "Ab*c";
greedy Matching: regular expressions tend to match the maximum length, which is called greedy matching. As above using pattern p to match string str, the result is matched to:abcaxc(ab*c).
non-greedy match : just match to the result is good, fewer match characters. As above using pattern p to match string str, the result is matched to:ABC(AB*C).
2. How to differentiate between two modes in programming
The default is greedy mode; Add a question mark directly after the quantifier? is the non-greedy mode.
Quantifier: {m,n}:m to n
*: Any number of
+: one to multiple
? : 0 or one
3. Program examples
Use snort's rule as part of a rule to match the text, matching the content part.
1 Import java.util.regex.Matcher; 2 Import Java.util.regex.Pattern; 3 4 public class Regulartest {5 6 public static void Main (string[] arg) {7 String text= "(content:\" RCPT t o root\ ";p cre:\" word\ ";)"; 8 String rule1= "content:\". +\ ""; Greedy mode 9 String rule2= "content:\". +?\ ""; Non-greedy mode System.out.println ("text:" +text), System.out.println ("Greedy mode:" +rule1); P1 =pattern.compile (rule1); Matcher m1 = p1.matcher (text), while (M1.find ()) { System.out.println ("Match result:" +m1.group (0)), }18 System.out.println ("non-greedy Mode:" +rule2); Pattern p2 =pattern.compile (rule2) Matcher m2 = p2.matcher (text), while (M2.find ()) { System.out.println ("Match result:" +m2.group (0)); }25 }26}
Execution Result:
4. Note
Not compiled successfully using Linux C? Non-greedy mode of the number.
A word on the Internet: the? only works for perl-based RegExp, not for POSIX ...
The greedy and non-greedy patterns of regular expressions