1, [ABC] A, B or C
[^ABC] Any character except A, B or C
[A-za-z] A to Z or A to Z, both characters are included
[A-d[m-p]] A to D or M to P: [A-dm-p] (set)
[A-z&&[def]] d,e or F (intersection)
2, * any character
\d number: [0-9]
\d non-numeric: [^0-9]
\s whitespace characters: [\t\n\x0b\f\r]
\s non-whitespace characters: [^\s]
\w Word character: [a-za-z_0-9]
\w non-word characters: [^\w]
3, greedy number of words
X? Not once or once.
x* 0 or more times
x+ one or more times
X{n} exactly n times
X{n,} at least n times
X{n,m} at least n times, but not more than M string
4, replace function
String s = "Hello123world";
String regex = "\\d";
String s2 = s.replaceall (Regex, "");
5, grouping function
Capturing groups can be numbered by calculating their opening brackets from left to right, ((A) (B (C))) There are 4 such groups
1 ((A) (B (C)))
2 (A)
3 (B (C))
4 (C)
Application: Overlapping word cutting: "SDQQFGKKKHJPPPPKL";
String regex = "(.) \\1+ "; string[] arr = s.split (regex);
Application: Put the string "I I ...." I... I-I-I ... Want to ... To learn .... Learn to learn. School of learning, knitting, knitting, knitting, ... Regulation Regulation ... "Output as" I want to learn to program "
String s = "I am ...." I... I-I-I ... Want to ... To learn .... Learn to learn. School of learning, knitting, knitting, knitting, ... Regulation Regulation ... Process ";
String s2 = s.replaceall ("\\.+", "" ");
String s3 = S2.replaceall ("(.) \\1+ "," $ ");
6, pattern and Matcher
Pattern p = pattern.compile (a*b); Get to Regular expression
Matcher m = P.matcher ("Aaaaaab"); Get the matching device
Boolean B = m.matches (); To see if it matches, the match returns True.
Equivalent to System.out.println ("Aaaaaab". Matches ("A*b"));
Apply: Get the phone number in a string
String s = "My phone number is 18988888888, has used 18987654321, also used 18812345678";
String regex = "1[3578]\\d{9}";
Pattern p = pattern.compile (regex);
Matcher m = P.matcher (s);
while (M.find ()) System.out.println (M.group ()); We have to find the group first.
Java Regular Expressions