Question

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?

Was it helpful?

Solution

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}$

OTHER TIPS

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

You could also use:

[^\p{Alpha}]\p{Alpha}{2}$

Use Alnum instead if digits count as words. This does, however, fail if the entire string is only two characters long.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top