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
函数中使用正则表达式?
你可以使用Mather/Pattern
和appendReplacement
。
正则表达式:(?:^| )[^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
尝试使用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();
}