簡體   English   中英

如果字符串在Java中以特殊字符開頭,則如何大寫首字母?

[英]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/PatternappendReplacement

正則表達式(?:^| )[^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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM