如何在Java中将驼峰命名法转换为小写连字符命名法,当存在连续的大写字母时

6

我有一个字符串"B2BNewQuoteProcess"。当我使用Guava将其从驼峰式转换成小写连字符,如下所示:

CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,"B2BNewQuoteProcess");

我得到的是“b2-b-new-quote-process”。

我需要的是“b2b-new-quote-process”...

在Java中该怎么做?


使用 (?=[A-Z][a-z]) 替换为 -,然后将字符串转换为小写。 - ctwheels
非常好用!谢谢! - user27478
我已经将我的上面的评论转换为答案。 - ctwheels
请注意,除非您接受第二个“B”是一个单独的单词,否则您的原始字符串不是大驼峰。为了保持一致,您必须使用 B2bNewQuoteProcess(看起来有点丑)。 - maaartinus
3个回答

11

编辑

为了防止行首出现-,请使用以下替代方案而非我的原回答:

(?!^)(?=[A-Z][a-z])

代码

在此查看正则表达式的使用情况

(?=[A-Z][a-z])

替换:-

注意:上面的正则表达式不会将大写字符转换为小写字符;它只是在应该有 - 的位置插入它们。在下面的Java代码中使用 .toLowerCase() 将大写字符转换为小写字符。

用法

点击此处查看示例代码

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        final String regex = "(?=[A-Z][a-z])";
        final String string = "B2BNewQuoteProcess";
        final String subst = "-";
        
        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(string);
        
        // The substituted value will be contained in the result variable
        final String result = matcher.replaceAll(subst);
        
        System.out.println("Substitution result: " + result.toLowerCase());
    }
}

解释

  • (?=[A-Z][a-z]) 正向先行断言,确保其后紧跟一个大写字母和一个小写字母。这被用作位置的断言。替换操作仅在与此断言匹配的位置插入连字符 -

1
@MariusSoutier 没错,我已经编辑了我的答案,包括了这种情况的修复。 - ctwheels

1

Java 8及以下版本的方法

使用此方法来转换任何驼峰字符串。您可以选择任何类型的分隔符。

private String camelCaseToLowerHyphen(String s) {
    StringBuilder parsedString = new StringBuilder(s.substring(0, 1).toLowerCase());
    for (char c : s.substring(1).toCharArray()) {
      if (Character.isUpperCase(c)) {
        parsedString.append("_").append(Character.toLowerCase(c));
      } else {
        parsedString.append(c);
      }
    }
    return parsedString.toString().toLowerCase();
  }
}

参考代码来自:http://www.java2s.com/example/java-utility-method/string-camel-to-hyphen-index-0.html


这段代码可以将驼峰式命名的字符串转换为连字符分隔的格式。

1
驼峰式命名 小写连字符 应该为
B2BNewQuoteProcess b2-b-new-quote-process b2b-new-quote-process
BaBNewQuoteProcess ba-b-new-quote-process
B2NewQuoteProcess b2-new-quote-process
BABNewQuoteProcess b-a-b-new-quote-process bab-new-quote-process

因此:

  • 大写字母后面的数字也算作大写字母
  • 如果有N+1个“大写字母”,前N个大写字母组成一个单词

修正错误结果的方法是:

String expr = "b2-b-new-quote-process";
expr = Pattern.compile("\\b[a-z]\\d*(-[a-z]\\d*)+\\b")
    .matcher(expr).replaceAll(mr ->
        mr.group().replace("-", ""));

这个搜索在单词边界(\b)之间查找一串带有任意数字的字母序列,接着是连字符加上带有任意数字的字母序列的重复。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接