user20843966
user20843966

Reputation:

Matching the second to the last word

I have the following line:

19 crooks highway Ontario

I want to match anything that comes before the last space (whitespace). So, in this case, I want to get back

highway

I tried this:

([^\s]+)

Upvotes: -1

Views: 56

Answers (2)

CinCout
CinCout

Reputation: 9619

Use this:

\s+(\S+)\s+\S*$

  1. Use $ anchor to match the end of the line
  2. \s+\S*$ matches one or more spaces followed by zero or more non-whitespaces at the end of the line
  3. The desired result is captured in the capturing group

Demo

Upvotes: 1

Hao Wu
Hao Wu

Reputation: 20699

You may use a lookahead to do it:

\S+(?=\s\S*$)
\S+       any non-whitespace characters, repeat 1+ times (equivolent to [^\s]+)
(?=...)   lookahead, the string after the previous match must satifies the condition inside
\s\S*$    any non-whitespace characters preceded by a whitespace, then the end of the string

See the test case

Upvotes: 1

Related Questions