Package Pack;import Java.util.regex.matcher;import Java.util.regex.pattern;public class Demo {public static void main ( String[] args) {//method1 ();//Match//method2 ();//Cut//method3 ();//replace///The front is just a string method */ METHOD4 (); } public static void Method1 () {String QQ = "1881265"; String regex1 = "[1-9]\\d{4,14}"; SYS (Qq.matches (REGEX1)); Whether to conform to the regex rule String s = "E"; String regex = "[A-za-z]"; The letter//string regex = "[a-d[m-p]]"; A to D or M to p/* \d number [0-9] * \d non-numeric [^0-9] * \s whitespace character * \s non-whitespace character * \w Word character [a-za-z0-9_] * \w non-word character * * * * X? Once or 0 times * x* 0 times or more * x+ once or more * x{n} exactly n times * x{n,} at least n times * x{n,m} n times to M Times * */String regex = "\\d"; SYS (s.matches (regex)); } public static void Method2 () {/*string s = "Zhang Li san"; String regex = "\\s+"; string[] arr = s.split (regex); for (string ss:arr) sys (SS); */* String s = "Zhang.li.san"; String regex = "\ \."; \. Represents any character in the regular expression, \ \. Represents the ordinary point, cannot be used directly. Cut, it is special character string[] arr = s.split (regex); for (String Ss:arr) sys (SS); *//*string s = "Www\\abs\\1.txt"; String regex = "\\\\"; string[] arr = s.split (regex); for (string ss:arr) sys (SS); */String s = "Wekkyduffopxxxs"; Cut by overlapping words/* to complete the cut by overlapping words, in order for the rule to be reused, the rules can be encapsulated into a group, complete with (), the groups are numbered, starting from 1 */String regex = "(.) \\1+ "; Parentheses are the concept of a group, \1 is re-appearing, \1+ is one or more string[] arr = s.split (regex); for (String Ss:arr) sys (SS); } public static void Method3 () {String s = "wj3374zns399nvn9999klf3333"; Replace number with # # String regex = "[0-9]"; S.replaceall (Regex, "#"); SYS (s); /*string s = "Wekkyduffopxxxs"; Replace the overlapping words with a single, such as: zzzz->z String regex = "(.) \\1+ "; S.replaceall (Regex, "$"); SYS (s); */} public static void Method4 () {String s = "Zhas ASB cjcdj CSJ Cbbdv"; String regex = "[A-z]{3}"; Encapsulates a rule into an object Pattern p = pattern.compile (regex); Gets the match object Matcher m = P.matcher (s); SYS (m.matches ()); Match all, false, note: The pointer moves backwards, affecting the following result while (M.find ()) {sys (m.group ())); Match to the string sys (M.start () + "..." +m.end ()); Matches the string to the beginning and end of the}} public static void Sys (Object obj) {System.out.println (obj); }}
Summary of Java Regular Expressions