I want to make a regex that matches all words with a specific length.
Example of the string I have:
"I ABCDE FGH IG KLMNOPQ RS T"
I want to match all words having length less than 3 letters (In this case I
, IG
, RS
and T
).
Here are the alternatives that I made:
Alt1:
Regex: ( |^)([A-Z]{1,2})( |$)
: Link1
Explanation: Matching any word with a length of 2 or 1 uppercase letters that is preceded by a space or in the beginning of the string (( |^)
) and followed by a space or at the end of the string (( |$)
).
The problem is that I get positive match for the blank spaces which I don't want. And I don't get match for the T
.
Alt2:
Regex: \w{1,2}\b
: Link2
Explanation:
match a word of at most 2 characters as long as its the only contents of the string
(I found it in this answer)
The problem is that I get matches of every last 2 letters from every word (DE
, GH
and PQ
) which is wrong in my case.