lastWord method

String lastWord()

Extracts the last word from the string.

Returns an empty string if no word characters are found. Includes any trailing punctuation as part of the word.

Example:

'This is a sentence.'.lastWord()           // 'sentence.'
'hello world'.lastWord()                   // 'world'
'well-being'.lastWord()                    // 'well-being'
'!!!no words!!!'.lastWord()                // ''

Implementation

String lastWord() {
  final match = RegExp('([$wordChars]+(?:-[$wordChars]+)*)[^$wordChars]*\$').firstMatch(this);
  return match?.group(1)?.trim() ?? '';
}