Reputation: 37
My goal is to get the last word of a string, no matter what the word is.
With a lot of trials and error I got kinda lucky with the following code, because instead of \w+ I tried \W+ and got a result I could work with.
But my actual code (the one you don't see here) is kinda messy, so my question is; What is the right compile regex to use to get the last word, or two words?
Thanks in advance!
import re
var = ' hello my name is eddie '
r = re.compile(r'\S+\W+$')
r2 = r.findall(var)
print(r2)
#result ['eddie ']
Upvotes: 1
Views: 171
Reputation: 18611
Use
import re
var = ' hello my name is eddie '
r_last_word = re.compile(r'\S+(?=\s*$)')
r_last_but_one = re.compile(r'\S+(?=\s+\S+\s*$)')
print(r_last_word.findall(var))
print(r_last_but_one.findall(var))
Results:
['eddie']
['is']
See proof.
\S+(?=\s*$)
- one or more non-whitespace characters that may have optional whitespaces after up to the end of string.
\S+(?=\s+\S+\s*$)
- one or more non-whitespace characters that may have one or more whitespace characters, one or more non-whitespace characters and then optional whitespaces after up to the end of string.
Upvotes: 2