Replace last word in string if it is 2 characters using regular expression

I am trying to replace the last word of a string if it contains 2 characters using a regular expression. I used [a-zA-Z]{2}$, but find the last 2 characters of the string. I do not want to replace the last word if it is not equal to 2 characters, how can I do this?

+3
source share
3 answers

Before the two letters, you need to match the word boundary ( \b):

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

This will match any two latin letters that appear at the end of the line if they are not preceded by the word symbol (this is a latin letter, number or underscore).

, , lookbehind, :

(?<![a-zA-Z])[a-zA-Z]{2}$
+6

\\b\\w\\w\\b$ ( java-)

: \\b\\w\\w$ . ( \b\w\w$ , java.. . )

+3

You can also use:

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

Use Alnuminstead of numbers, counting words. This, however, fails if the entire string is only two characters long.

0
source

All Articles