willywonka15
willywonka15

Reputation: 97

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);
}

I want to capitalize first letter of each word. I use WordUtils function. And my string has special characters like '*', - etc. How can I use regex with capitalizeFully function?

Upvotes: 2

Views: 2195

Answers (2)

Srdjan M.
Srdjan M.

Reputation: 3405

You can use Mather/Pattern and appendReplacement.

Regex: (?:^| )[^a-z]*[a-z]

Details:

  • (?:^| ) Non-capturing group, match ^ (asserts position at start of a line) or ' ' (space)
  • [^a-z]* Matches any non lowercase word character between zero and unlimited times
  • [a-z] Matches any lowercase word character

Java code:

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);

Output:

*Tried String

Code demo

Upvotes: 5

Nomade
Nomade

Reputation: 1748

Try to use WordUtils.capitalize function where the , that's gonna capitalize first letter of each word in a String.

Not that WordUtils in commons-lang lib is Deprecated.

Other way using Java custom function:

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();
}

Upvotes: 3

Related Questions