1. package com.zoro.test;
    2. /**
    3. * (.+(?=\()) 获取 ( 前的字符串
    4. *
    5. * @author yx.Jiang
    6. * @desc
    7. * @date 2022-04-28 21:54
    8. */
    9. public class ReplaceStr {
    10. public static void main(String[] args) {
    11. String tel = "+86(10)5730-4332";
    12. String format = format(tel);
    13. System.out.println("format = " + format);
    14. }
    15. /**
    16. * 格式化固话号码
    17. *
    18. * @param tel 固话 +86(10)5730-4332
    19. * @return 格式化后的电话号码
    20. */
    21. private static String format(String tel) {
    22. //判空 isNotBlank(tel)
    23. //获取省号
    24. String provinceNo = "";
    25. if (tel.contains("(") && tel.contains(")")) {
    26. //10
    27. provinceNo = tel.substring(tel.indexOf("(")+1, tel.indexOf(")"));
    28. }
    29. //去除国号及省号 +86(10)
    30. if (tel.contains("+") && tel.contains(")")) {
    31. //5730-4332
    32. tel = tel.replaceAll("(\\+)(\\d|\\()*(\\))", "");
    33. }
    34. //省号长度为2补0
    35. if (provinceNo.length() == 2) {
    36. //010
    37. provinceNo = "0" + provinceNo;
    38. }
    39. return String.format("%s-%s",provinceNo, tel);
    40. }
    41. }