Assuming you have a string like these 2 examples:
- ABC DEF GHI JKL MNOPQR STUVWX
- 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]*$
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]*$)