Jenveloper
Jenveloper

Reputation: 45

Extracting last word from each line using regex

I would like to extract the last word of each line using regex. Most of the last words are built up like this:

sfdsa AAAAB3NzaCLkc3M

gadsgadsg AAAB3NzaCl/Ezfl

dogjasdpgpds AAAB3Nza/ClBAm+4lj

I already tried:

lastwords = re.findall(r'\s(\w+)$', content, re.MULTILINE)

Upvotes: 2

Views: 6222

Answers (1)

Mustofa Rizwan
Mustofa Rizwan

Reputation: 10466

You need to try that:

\s*([\S]+)$

Regex 101 Demo

Explanation:

  • \s* zero or more whitespace characters
  • [\S]+ followed by one or more non whitespace characters
  • $ followed by end of line.

By that way, you are guaranteed to match the last occurance of whitespace characters as that will be followed by no further whitespace characters.

The reason behind your regex did not work because \w+ only covers A-Za-z0-9_ So, / doesn't match in two of your example.

Upvotes: 2

Related Questions