Search code examples
javaregexword-boundary

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?


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