Home > Net >  First 3 characters of last word using regex?
First 3 characters of last word using regex?

Time:09-25

Assuming you have a string like these 2 examples:

  1. ABC DEF GHI JKL MNOPQR STUVWX
  2. ABC DEF GHI JKL MNOPQR STU VWX

In the first example, I want to return STU, and in the second, VWX

  • I know that I can use ^.{3} to get the first 3 letters of the entire string, e.g. ABC.
  • I know that I can use [A-Za-z] $ to get the final word, e.g. STUVWX, and VWX.
  • What I can't figure out is how to combine this into one regex that returns STU and VWX.

CodePudding user response:

You could use a capture group to match 3 chars A-Za-z, and match optional chars until the end of the string.

To prevent a partial match, you might prepend a word boundary \b

\b([A-Za-z]{3})[A-Za-z]*$

Regex demo

Another option using lookarounds to get a match only could be asserting a whitespace boundary to the left, and assert optional chars A-Za-z till the end of the string to the right.

(?<!\S)[A-Za-z]{3}(?=[A-Za-z]*$)

Regex demo

  • Related