Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a regex replacement term for the uppercase/lowercase version of a back reference? [duplicate]

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.

?

like image 916
Bohemian Avatar asked Dec 19 '13 05:12

Bohemian


People also ask

How to check for special characters in regex?

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 "(" .

How do you uppercase in regular expressions?

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.

How do I replace a word in a regular expression?

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.


1 Answers

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();
}
like image 81
Infinite Recursion Avatar answered Oct 13 '22 19:10

Infinite Recursion