Paul P
Paul P

Reputation: 41

Regex match last word in string ending in

I want to regex match the last word in a string where the string ends in ... The match should be the word preceding the ...

Example: "Do not match this. This sentence ends in the last word..."

The match would be word. This gets close: \b\s+([^.]*). However, I don't know how to make it work with only matching ... at the end.

This should NOT match: "Do not match this. This sentence ends in the last word."

Upvotes: 4

Views: 2198

Answers (2)

The fourth bird
The fourth bird

Reputation: 163217

If you use \s+ it means there must be at least a single whitespace char preceding so in that case it will not match word... only.

If you want to use the negated character class, you could also use

([^\s.]+)\.{3}$
  • ( Capture group 1
    • [^\s.]+ Match 1+ times any char except a whitespace char or dot
  • ) Close group
  • \.{3} Match 3 dots
  • $ End of string

Regex demo

Upvotes: 2

Andreas Louv
Andreas Louv

Reputation: 47099

You can anchor your regex to the end with $. To match a literal period you will need to escape it as it otherwise is a meta-character:

(\S+)\.\.\.$

\S matches everything everything but space-like characters, it depends on your regex flavor what it exactly matches, but usually it excludes spaces, tabs, newlines and a set of unicode spaces.

You can play around with it here:

https://regex101.com/r/xKOYa4/1

Upvotes: 0

Related Questions