MSaudi MSaudi - 1 year ago 57
Java Question

How to match just 1 or 2 chars with regex

i want regx to match any word of 2 or 1 characters example ( is , an , or , if, a )

i tried this :-

int scount = 0;
String txt = "hello everyone this is just test aa ";
Pattern p2 = Pattern.compile("\\w{1,2}");
Matcher m2 = p2.matcher(txt);

while (m2.find()) {

but got wrong matches.

Answer Source

You probably want to use word boundary anchors:

Pattern p2 = Pattern.compile("\\b\\w{1,2}\\b");

These anchors match at the start/end of alphanumeric "words", that is, in positions before a \w character if there is no \w character before that, or after a \w character if there is no \w character after that.