![](/img/trans.png)
[英]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.