Matching second last word in sentence through regular expression?
By John Peck •
I'm looking for a way to match the second last word on a line, such as this:
123 Smith St Melbourne VIC 3000I'd like to match just "VIC". Does someone have a regex I can use?
2 Answers
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]+$)
To match the second word from the end use: (?!(\w+\s\w+$))|(?:.+?)
To replace everything other than the second last word use: (?!(\w+\s\w+$))(?:.+?)
You might need to do something about special characters you may have, though.