l33t
l33t

Reputation: 19937

Extract all but the last word + the last word

Using Regex POSIX. Given a sentence, how can I extract all but the last word + the last word (preferably without the space between "to" and "2")? In my case, the last word will always be a number.

E.g.: The string: Let's count from 1 to 2 is split into Let's count from 1 to and 2

Upvotes: 0

Views: 2108

Answers (3)

hwnd
hwnd

Reputation: 70722

You could use the following regex.

^(.+)\s(\d+)$

Upvotes: 1

Phil Tune
Phil Tune

Reputation: 3305

If your last word will always be a digit:

/^([\S ]+) (\d+)$/
  • Starting at the beginning
  • All word characters and spaces (1 or more times)
  • Don't grab the space before the last word
  • All digits (1 or more times)
  • End of the line/string

Upvotes: 3

Gilles Quénot
Gilles Quénot

Reputation: 185015

Try doing this :

/(.*?)\s+(\w+)$/

Check http://regex101.com/r/zK3iQ2/1

Upvotes: 2

Related Questions