Home > database >  Matching the second to the last word
Matching the second to the last word

Time:12-23

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] )

CodePudding user response:

It is expected to use a lookahead in this situation, try this out

\S (?=\s\S*$)

This works

CodePudding user response:

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

CodePudding user response:

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

  • Related