Matching second last word in sentence through regular expression

regex

I'm looking for a way to match the second last word on a line, such as this:

123 Smith St Melbourne VIC 3000

I'd like to match just "VIC". Does someone have a regex I can use?

Best Answer

Depending of what is a "word" for you, you can use:

  • A word is 1 or more characters that is not a space
    • \S+(?=\h+\S+$) will match 1 or more not space followed by 1 or more horizontal space then 1 or more non space
  • A word is 1 or more alphabetic character
    • [a-zA-Z]+(?=\h+[a-zA-Z]+$)
  • A word is 1 or more alphanumeric character
    • [a-zA-Z0-9]+(?=\h+[a-zA-Z0-9]+$)
  • A word is 1 or more any letter in any language
    • \pL+(?=\h+\pL+$)
  • A word is 1 or more any letter or digit in any language
    • [\pL\pN]+(?=\h+[\pL\pN]+$)
Related Question