I'm looking to capitalise each part of a string that precedes/follows a special character and found this post which does the trick nicely. Only problem is it also sees characters which are special alpha characters (eg ô, ê, ë...) as part of the check. How do I get this to ignore those, or rather see them as acceptable alpha characters?

public static String capitaliseString(String word) {
   String name = '';
   Matcher m = Pattern.compile('(\\w+|\\W+)').matcher(word);
   while (m.find())
     name += m.group().toLowerCase().capitalize();
   system.debug('####util_helper capitaliseString: ' + word + ' ## ' + name);
   return name;

For example, if I pass it a string like o'hägen-daß I need it to return O'Hägen-Daß, but instead it returns O'HÄGen-Daß as it sees the ä as a special character.

2 Answers 2


\w is the shortcut character class for ascii word characters; a-z, A-Z, _, 0-9

You'll need a more extensive character class.

From this question on StackOverflow, it appears that Java allows positive and negative matching on larger unicode categories and blocks using \p{<identifier>} (positive match) and \P{<identifier>} (negative match).

The difference being what you might expect. Lower case 'p' = do a positive match, upper case 'P' = do a negative match.

Since Apex compiles to Java bytecode, figured it was worth a shot. Turns out that we do have the ability to use these (we just need to change the one backslash to two, as usual).

Simply replacing your regex '(\\w+|\\W+)' with one that does the same, but for all unicode (not just Latin++) characters (\\p{L}+|\\P{L}+) seems to return the result you want.

That could likely be narrowed down a bit.


I think this will be helpful.

public static String toProperCase(String request){
    List<String> responseList = new List<String>();
    request = request.toLowerCase().normalizeSpace(); // To convert to lower case and remove unwanted spaces within string
    List<String> requestList = request.splitByCharacterType(); // Split the string at different character type
    for(String word : requestList){
        responseList.add(word.capitalize()); // Capitalize first character of each split word
    return String.join(responseList, '');
  • Welcome to Salesforce Stack Exchange (SFSE)! Your contribution is welcome, but your answer is essentially a "code dump" which is frowned upon. Here on SFSE the why (explanation) is often as or more important than the how (code) in an answer. Please edit your answer to explain - even briefly (but enough to understand) - what in your code is different from the code posted in the question & why that solves the problem. (In other words, how exactly splitByCharacterType() helps?) Maybe include actual output using the OPs example.
    – Moonpie
    Commented May 4, 2022 at 19:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .