Here are some easy to confuse Java regular expressions, and then there are a few examples to share with you
String cutting
Demo1
String str = "Zhangsan,lisi,wangwu"; String reg = ",";//note here may be error prone, of course this demo can be directly written ', ' string[] arr = Str.split (reg);
Demo2
String str = "Zhangsan Lisi Wangwu"; String reg = "+";//here indicates that there is at least one space string[] arr = Str.split (reg);
Demo3
String str = "Zhangsan.lisi.wangwu"; String reg = "\ \."; /Note that here's the. must be escaped, backslash inside the string also need to escape, so there appears double//Slash string[] arr = Str.split (reg);
Demo4
String str = "C:\\test\\test"; String reg = "\\\\";//Similarly, each backslash needs to be escaped so there are four backslashes string[] arr = Str.split (reg);
Demo5
String str = "Zhangsannnlisiiiiwangwu"; String reg = "(.) \\1 ";//denotes overlapping words, if multiple occurrences occur (.) \\1+. Where 1 corresponds to the group number, indicating from 1//start. The way to use it is to get string[] arr = Str.split (reg) in a \ n way;
Regular expression substitution
Demo1
String str = "Zhan333gsannnlisiiiiw3333angwu"; String reg = "\\d+"; Normal replacement can be string[] arr = Str.replaceall (Reg, "#");
Demo2 Replace the contents of the first group
String str = "Zhan333gsannnlisiiiiw3333angwu"; String reg = "(.) \\1 "; string[] arr = Str.replaceall (Reg, "$");//The result is that zhan3gsanlisiw3angwu,$ is holding the first set of rules
Regular Expression Lookup
Demo1
String str = "Zhan333gsannnlisiiiiw3333angwu"; String reg = "[A-z]{3}"; Pattern p = pattern.compile (reg); Matcher m = p.matcher (str), while (M.find ()) {System.out.print (M.group ());}
Demo2
String str = "Zhan333gsannnlisiiiiw3333angwu"; String reg = "\\b[a-z]{3}\\b"; Note that the word boundary is added here with the Pattern P = pattern.compile (reg); Matcher m = p.matcher (str), while (M.find ()) {System.out.print (M.group ());}
This article is from the "Presumptuous Java" blog, please be sure to keep this source http://fun4java.blog.51cto.com/6609513/1661318
Java Regular Expressions (iii)