0

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.

1

\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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.