1

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   ']
2
  • 3
    Like this? (\S+)\s*$ regex101.com/r/BcF2vb/1 Commented Sep 16, 2020 at 15:00
  • or var.strip().split(" ")[-1], and [-2:] if you need 2 words. Commented Sep 16, 2020 at 15:05

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.