1. Backslash and escape character
No more nonsense, just on the demo.
Public Static voidMain (string[] args) {//TODO auto-generated Method StubString phonenum= "28516885191"; Isphonenum (Phonenum); } //13800000876 Public Static voidisphonenum (String phonenum) {string regex= "1[34578][0-9]{9}"; String Regex2= "1[34578]\\d{9}"; Booleanisphonenum=phonenum.matches (regex); System.out.println ("Is Phonenum?" "+isphonenum); }
Summarize
/*
* Regular expression matches the rules of numbers, which can be expressed by [0-9] and \d,
* But in the Java language, \ In the string itself is an escape character, meaning \ is not the backslash of the character itself \, but it has a special meaning (escaped)
* Regular, \d, is the ordinary backslash and d a piece, the number (that is, the \ is not the escape character in the regular). So in the Java language, we can't directly use \d to represent numbers,
* Need this: \\d the previous backslash, is the escape character, the second backslash escape character representable translated into a normal character backslash
*
* */
Use and cutting of the group:
Public Static void Main (string[] args) { // TODO auto-generated method stub String string= " Andittttbobmmmmmmmmmmmcyanxxdenim "; String Regex= "(.) \\1+ "; String[] Strings= string.split (regex); for (String string2:strings) { System.out.println ("Name:" + string2); } }
Output
Name:andi
Name:bob
Name:cyan
Name:denim
Summarize:
In an expression ((A) (B (C) )), there are four groups:
1 ((A) (B (C)))
2 (A)
3 (B (C))
4 (C)
Group 0 always represents an entire expression
3. Use and replacement of the group:
Public Static voidMain (string[] args) {String str1_1= "Andittttbobmmmmmmmcyanxxdenim";//Source StringString regex1= "(.) \\1+ "; //target string: Andi#bob#cyan#denimString str1_2= Str1_1.replaceall (Regex1, "#"); System.out.println ("Str1_2:" +str1_2); String Str2_1= "Andittttbobmmmmmmmcyanxxdenim";//Source StringString regex2= "(.) \\1+ "; //target string: AnditbobmcyanxdenimString str2_2= Str2_1.replaceall (REGEX2, "$"); System.out.println ("Str2_2:" +str2_2); }
Output
Str1_2:andi#bob#cyan#denim
Str2_2:anditbobmcyanxdenim
Summary: In the String.replaceall () method, use the $ symbol to let the second parameter use the value of the first parameter
4.1 Cutting:
Public Static void Main (string[] args) { // TODO auto-generated method stub String path1= "com/ westward/p/5399166 "; // Source String // target string com.westward.5399166 String regex= "/"; String path2= Path1.replaceall (Regex, ".") ); System.out.println (path2); }
Output
com.westward.p.5399166
4.2 Cutting:
Public Static void Main (string[] args) { // TODO auto-generated method stub String str= "15800001111"; // Source String // target string: 158****1111; String regex= "(\\d{3}) \\d{4} (\\d{4})"; String str2= Str.replaceall (Regex, "$1****$2"); System.out.println ("str2:" +str2); }
Output
str2:158****1111
Use of regular expressions in Java 1