[英]How can capitalize first letter if string starts with special character in Java?
public static void main(String [] args) {
String patternString = "\"[^a-zA-Z\\s]]+\"";
String s = WordUtils.capitalizeFully("*tried string", patternString.toCharArray());
System.out.println(s);
}
我想將每個單詞的首字母大寫。 我使用WordUtils
函數。 而且我的字符串具有特殊字符,例如'*'
--等。如何將regex與capitalizeFully
函數一起使用?
嘗試在其中使用的WordUtils.capitalize
函數,該函數將大寫String
中每個單詞的首字母。
並不是commons-lang lib中的
WordUtils
已棄用 。
使用Java自定義函數的其他方法:
public String upperCaseWords(String sentence) {
String words[] = sentence.replaceAll("\\s+", " ").trim().split(" ");
StringBuffer newSentence = new StringBuffer();
int i =0;
int size = words.length;
for (String word : words) {
newSentence.append(StringUtils.capitalize(word));
i++;
if(i<size){
newSentence.append(" "); // add space
}
}
return newSentence.toString();
}
您可以使用Mather/Pattern
和appendReplacement
。
正則表達式 : (?:^| )[^az]*[az]
細節:
(?:^| )
非捕獲組,匹配^
(在行首聲明位置) 或 ' '
(空格) [^az]*
匹配零到無限次之間的任何非小寫單詞字符 [az]
匹配任何小寫字母字符 Java代碼 :
String input = "*tried string".toLowerCase();
Matcher matcher = Pattern.compile("(?:^| )[^a-z]*[a-z]").matcher(input);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(result, matcher.group().toUpperCase());
}
matcher.appendTail(result);
輸出:
*Tried String
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.