用于将CamelCase转换为java中的camel_case的正则表达式 [英] Regex for converting CamelCase to camel_case in java

查看:610
本文介绍了用于将CamelCase转换为java中的camel_case的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解为什么没有给出使用正则表达式将 FooBar 这样的字符串转换为 Foo_Bar 所需的输出给出 Foo_Bar _ 。我可以用String.substring substring(0,string.length() - 2)做一些事情,或者只是替换掉最后一个字符,但我认为有一个更好的解决方案这样的场景。

I understand why the desired output is not given for converting using regex a string like FooBar to Foo_Bar which instead gives Foo_Bar_. I could have done something with String.substring substring(0, string.length() - 2) or just replaced the last character, but I think there is a better solution to such a scenario.

这是代码:

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
*/

问题:寻找更简洁的方法来获得所需的输出?

Question: Looking for a neater way to get the desired output?

推荐答案

看到这个问题 CaseFormat 来自番石榴

See this question and CaseFormat from guava

在您的情况下,例如:

CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, "SomeInput");

这篇关于用于将CamelCase转换为java中的camel_case的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆