ajm*_*tin 72 java regex string
我明白了为什么使用正则表达式的字符串转换一样没有给出所需的输出FooBar到Foo_Bar这反而给了Foo_Bar_.我可以用String.substring做一些事情substring(0, string.length() - 2)或者只是替换掉最后一个字符,但我认为这种情况有更好的解决方案.
这是代码:
String regex = "([A-Z][a-z]+)";
String replacement = "$1_";
"CamelCaseToSomethingElse".replaceAll(regex, replacement);
/*
outputs: Camel_Case_To_Something_Else_
desired output: Camel_Case_To_Something_Else
*/
Run Code Online (Sandbox Code Playgroud)
问题:寻找更简洁的方法来获得所需的输出?
小智 146
看到这个问题,CaseFormat来自番石榴
在你的情况下,像:
CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "SomeInput");
Run Code Online (Sandbox Code Playgroud)
cle*_*ion 58
将小写和大写绑定为两组,就可以了
public class Main
{
public static void main(String args[])
{
String regex = "([a-z])([A-Z]+)";
String replacement = "$1_$2";
System.out.println("CamelCaseToSomethingElse"
.replaceAll(regex, replacement)
.toLowerCase());
}
}
Run Code Online (Sandbox Code Playgroud)
小智 36
您可以使用以下代码段:
String replaceAll = key.replaceAll("(.)(\\p{Upper})", "$1_$2").toLowerCase();
Run Code Online (Sandbox Code Playgroud)
我无法提供 RegEx,无论如何它都会非常复杂。
试试这个带有首字母缩略词自动识别功能的功能。
不幸的是 Guava lib 不会自动检测大写首字母缩略词,因此“bigCAT”将被转换为“BIG_C_A_T”
/**
* Convert to UPPER_UNDERSCORE format detecting upper case acronyms
*/
private String upperUnderscoreWithAcronyms(String name) {
StringBuffer result = new StringBuffer();
boolean begin = true;
boolean lastUppercase = false;
for( int i=0; i < name.length(); i++ ) {
char ch = name.charAt(i);
if( Character.isUpperCase(ch) ) {
// is start?
if( begin ) {
result.append(ch);
} else {
if( lastUppercase ) {
// test if end of acronym
if( i+1<name.length() ) {
char next = name.charAt(i+1);
if( Character.isUpperCase(next) ) {
// acronym continues
result.append(ch);
} else {
// end of acronym
result.append('_').append(ch);
}
} else {
// acronym continues
result.append(ch);
}
} else {
// last was lowercase, insert _
result.append('_').append(ch);
}
}
lastUppercase=true;
} else {
result.append(Character.toUpperCase(ch));
lastUppercase=false;
}
begin=false;
}
return result.toString();
}
Run Code Online (Sandbox Code Playgroud)
为什么不简单地将前面的字符匹配为行首$呢?
String text = "CamelCaseToSomethingElse";
System.out.println(text.replaceAll("([^_A-Z])([A-Z])", "$1_$2"));
Run Code Online (Sandbox Code Playgroud)
请注意,可以安全地在已经骆驼保护的东西上执行此版本。
| 归档时间: |
|
| 查看次数: |
62629 次 |
| 最近记录: |