栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java实现字符串驼峰和下划线格式的转换

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java实现字符串驼峰和下划线格式的转换

基本每个项目都会使用到驼峰格式和下划线格式之间的转换,这里提供一个使用正则进行转换的例子
  1. 代码如下:
public class Test {

    public static void main(String[] args) {
        String str = "helloWordTestHe";
        System.out.println(xX2x_x(str));
        String str1 = "hello_Word_tESt_he";
        System.out.println(x_x2xX(str1));
    }
    
    public static String xX2x_x(String str) {
        Pattern compile = Pattern.compile("[A-Z]");
        Matcher matcher = compile.matcher(str);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()) {
            matcher.appendReplacement(sb,  "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    
    public static String x_x2xX(String str) {
        str = str.toLowerCase();
        Pattern compile = Pattern.compile("_[a-z]");
        Matcher matcher = compile.matcher(str);
        StringBuffer sb = new StringBuffer();
        while(matcher.find()) {
            matcher.appendReplacement(sb,  matcher.group(0).toUpperCase().replace("_",""));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
  1. 运行结果如下:
    hello_word_test_he
    helloWordTestHe
  2. api解读
    matcher.appendReplacement(StringBuffer sb, String replacement) :将当前匹配的子串替换为指定字符串,并且将替换后的子串与上次操作后的字符串拼接到一起后添加到一个 StringBuffer 对象里,例如上面的xX2x_x方法中操作helloWordTestHe这个字符串。每次的操作结果是:
    hello_w
    hello_word_t
    hello_word_test_h
    hello_word_test_he
    appendTail(StringBuffer sb):将最后一次匹配后剩余的字符串添加到StringBuffer 对象中
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/825609.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号