[英]regular expression to replace two (or more) consecutive characters by only one?
[英]regular expression replace 2 characters with one
我想对以下问题使用正则表达式:
SOME_RANDOM_TEXT
应转换为:
someRandomText
因此,_(任何字符)应该只用大写字母代替。 我使用工具发现了类似的东西:
_\w and $&
如何只获得替换的第二个字母? 有什么建议吗? 谢谢。
只需将String.split("_")
然后重新加入,将集合中每个字符串的首字母大写,可能会更容易。
请注意,Apache Commons有许多有用的字符串相关内容,包括join( )方法。
问题是Java.util.regex.Pattern不支持从小写到大写的转换。这意味着您将需要按照Brian的建议以编程方式进行转换。 另请参阅此线程
您也可以编写一个简单的方法来执行此操作。 它更复杂,但更优化:
public static String toCamelCase(String value) {
value = value.toLowerCase();
byte[] source = value.getBytes();
int maxLen = source.length;
byte[] target = new byte[maxLen];
int targetIndex = 0;
for (int sourceIndex = 0; sourceIndex < maxLen; sourceIndex++) {
byte c = source[sourceIndex];
if (c == '_') {
if (sourceIndex < maxLen - 1)
source[sourceIndex + 1] = (byte) Character.toUpperCase(source[sourceIndex + 1]);
continue;
}
target[targetIndex++] = source[sourceIndex];
}
return new String(target, 0, targetIndex);
}
我喜欢Apache公共库,但是有时候了解它的工作原理并能够为诸如此类的工作编写一些特定的代码是很好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.