Regular expressions have a powerful feature on string processing, and Sun has added support to it in JDK1.4.
The following is simple to say its four common functions:
Inquire:
String str = "ABC EFG ABC";
String regex = "a | f"; // means A or F
Pattern P = Pattern.Compile (regex);
Matcher M = P.matcher (STR);
Boolean RS = m.find ();
If there is regex in the STR, then rs is true, otherwise it is Flase. If you want to ignore your case when you look up, you can write a pattern p = pattern.compile (regex, pattern.case_insensitive);
extract:
String regex = ". (. ) $";
String str = "c: //dir1//dir2/name.txt";
Pattern P = Pattern.Compile (regex);
Matcher M = P.matcher (STR);
Boolean RS = m.find ();
For (int i = 1; i <= m.GroupCount (); i ) {
System.out.println (M.Group (i));
}
The above execution result is Name.txt, and the extracted string is stored in M.Group (i), where i is the maximum value of m.GroupCount ();
segmentation:
String regex = "::";
Pattern P = Pattern.Compile (regex);
String [] r = p.split ("xd :: abc :: cde");
After execution, R is {"XD", "ABC", "CDE"}, in fact, there is a simple method:
String str = "xd :: abc :: cde";
String [] r = Str.Split ("::");
Replace (delete):
String regex = "a "; // means one or more A
Pattern P = Pattern.Compile (regex);
Matcher M = P.matcher ("Aabbced a ccdeaa);
String s = m.ReplaceAll ("a");
The result is "abbced a ccdea"
If you write into an empty string, you can reach the delete function, such as:
String s = m.ReplaceAll ("");
The result is "BBCED CCDE"
Attachment:
/ D is equal to [0-9] digital / d equal to [^ 0-9] non-digital / S equal to [/ T / N / X0B / f / R] blank font / s equal to [^ / T / N / X0B / F / R] Non-blank character / w is equal to [A-ZA-Z_0-9] number or English word / W is equal to [^ a-za-z_0-9] non-numbers and English words ^ indicate the beginning of each line End of each line