Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last word in a string if it is 2 characters long using regex

I am trying to replace last word of a string if it is 2 characters long using regex. I used [a-zA-Z]{2}$ but it is finding last 2 characters of string. I don't want to replace the last word if it is not exactly 2 characters long, how can I do it?

like image 662
Praneeth Avatar asked Dec 01 '25 20:12

Praneeth


2 Answers

You need to match a word boundary (\b) before the two letters:

\b[a-zA-Z]{2}$

This will match any two Latin letters that appear at the end of a string, as long as they are not preceded by a 'word' character (which is a Latin letter, digit, or underscore).

In case you want to replace the word even if it is preceded by a digit or underscore, you might want to use a lookbehind assertion, like this:

(?<![a-zA-Z])[a-zA-Z]{2}$
like image 75
p.s.w.g Avatar answered Dec 03 '25 10:12

p.s.w.g


\\b\\w\\w\\b$ (regex in java flavor)

should work as well

Edit: in fact \\b\\w\\w$ should be enough. (or \b\w\w$ in non-java flavor.. see demo link)

like image 41
donfuxx Avatar answered Dec 03 '25 11:12

donfuxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!