Suppose I want to change a lowercase string to "title case"; where the first letter of every word is capitalized. Can this be done using a single call to replaceAll()
by using a modifier in the replacement expression?
For example,
str = str.replaceAll("\\b(\\S)", "???$1");
Where "???" is some expression that folds the case of the next letter.
I have seen this is other tools (like textpad), where \U
will fold the next letter to uppercase.
?
Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .
In the regex \U\w, \w is converted to uppercase while the regex is parsed. This means that \U\w is the same as \W, which matches any character that is not a word character.
To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.
Not possible with replaceAll. But you can use regex and split:
public String titleTextConversion(String text) {
String[] words = text.split("(?<=\\W)|(?=\\W)");
StringBuilder sb = new StringBuilder();
for (String word : words) {
if (word.length() > 0)
sb.append(word.substring(0, 1).toUpperCase()).append(word.substring(1).toLowerCase());
}
return sb.toString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With