I have a string that contains text in PascalCase and I need to extract first word from it and convert it to lowercase:
assert firstWord('PmdExtension') == 'pmd'
assert firstWord('PMDExtension') == 'p'
assert firstWord('Pmd') == 'pmd'
assert firstWord('CodeQualityExtension') == 'code'
static String firstWord(String word) {
return '???'
}
Let's focus only on valid PascalCase identifiers (without any other characters, numbers and always starting with capital letter).
What would be the simple and clean solution for my problem?
I've tried
word.split(/[A-Z]/).first().join(' ')
but it removes all uppercase letters, while I need to preserve them.
assert firstWord('PmdExtension') == 'pmd'
assert firstWord('PMDExtension') == 'p'
assert firstWord('Pmd') == 'pmd'
assert firstWord('CodeQualityExtension') == 'code'
assert firstWord('') == ''
assert firstWord(null) == ''
static String firstWord(String word) {
word ? word.split(/(?=\p{Lu})/)[0].toLowerCase() : ''
// A verbose way would be as below (omitting the null check for brevity)
// word[0].toLowerCase() + word[1..-1].takeWhile { Character.isLowerCase(it) }
}
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