首页 > 编程语言 > Java正则表达式工具方法汇总
2020
11-19

Java正则表达式工具方法汇总

1.获取某字符串中汉字的个数

...
  private int getChineseCount(String text) {
    String Reg = "^[\u4e00-\u9fa5]{1}$";// 正则
    int result = 0;
    for (int i = 0; i < text.length(); i++) {
      String b = Character.toString(text.charAt(i));
      if (b.matches(Reg))
        result++;
    }
    return result;
  }
...

2.使用正则替换某字符串中所有符合正则的字符串为指定字符串

//将str中的符合正则regu的字符串替换成replaceStr
...
  private static String replace(String str, String regu, String replaceStr) {
    Pattern pattern = Pattern.compile(regu);
    Matcher matcher = pattern.matcher(str);
    str = matcher.replaceAll(replaceStr);
    return str;
  }
...

3.驼峰式转换成大写下划线

...
  private String humpToLine(String str) {
    Pattern humpPattern = Pattern.compile("[A-Z]");
    Matcher matcher = humpPattern.matcher(str);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
      matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
    }
    matcher.appendTail(sb);
    return sb.toString().toUpperCase();
  }
...

4.大写下划线转换成驼峰式

...
  private String lineToHump(String str) {
    Pattern linePattern = Pattern.compile("_(\\w)");
    str = str.toLowerCase();
    Matcher matcher = linePattern.matcher(str);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
      matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
    }
    matcher.appendTail(sb);
    return sb.toString();
  }
...

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧