JAVA正则表达式语法示例与语法大全

电话号码转换

  1. public static void main(String[] args) {
  2. //原始电话号码
  3. String phoneNumber = "+1(111)222-3333";
  4. String phone = "";
  5. for (int i = 1; i < phoneNumber.length(); i++) {
  6. int ch = phoneNumber.charAt(i);
  7. if (ch >= '0' && ch <= '9') {
  8. phone += (char) ch;
  9. }
  10. }
  11. System.out.println(phone);
  12. //使用正则
  13. String phone2 = phoneNumber.replaceAll("\\D", "");
  14. System.out.println(phone2);
  15. }

image.png

去除标点符号

参考

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

image.png

反向引用

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

image.png