如果字符串以Java中的特殊字符开头,如何将首字母大写?

问题描述 投票:2回答:2
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功能。我的字符串有像'*'这样的特殊字符,等等。如何在capitalizeFully函数中使用正则表达式?

java regex string
2个回答
3
投票

你可以使用Mather/PatternappendReplacement

正则表达式:(?:^| )[^a-z]*[a-z]

细节:

  • (?:^| )非捕获组,匹配^(在一行开头断言位置)或' '(空格)
  • [^a-z]*匹配零和无限次之间的任何非小写单词字符
  • [a-z]匹配任何小写单词字符

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

Code demo


3
投票

尝试使用WordUtils.capitalize函数,它将在String中将每个单词的首字母大写。

不是WordUtils中的commons-lang lib已弃用。

使用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();
}
© www.soinside.com 2019 - 2024. All rights reserved.