JAVA正则表达式语法示例与语法大全
电话号码转换
public static void main(String[] args) { //原始电话号码 String phoneNumber = "+1(111)222-3333"; String phone = ""; for (int i = 1; i < phoneNumber.length(); i++) { int ch = phoneNumber.charAt(i); if (ch >= '0' && ch <= '9') { phone += (char) ch; } } System.out.println(phone); //使用正则 String phone2 = phoneNumber.replaceAll("\\D", ""); System.out.println(phone2);}

去除标点符号
参考
public static void main(String[] args) { String text = "+1(111)222-3333,23d:'asd-=*&sad123"; //"\\p{P}"表示匹配所有的Unicode标点符号, "\\s"表示匹配所有空白字符 String newText = text.replaceAll("\\p{P}", " ").replaceAll("\\s", " "); System.out.println(newText);}

反向引用
public class Main { public static void main(String[] args) { String s = "the quick brown fox jumps over the lazy dog."; String r = s.replaceAll("\\s([a-z]{4})\\s", " <b>$1</b> "); System.out.println(r); }}
