Find regex of specified length and start and end also specified in Java

I want to find all words of length 3, starting with "l" and ending with "f". Here is my code:

Pattern pt = Pattern.compile("\\bl.+?f{3}\\b");
Matcher mt = pt.matcher("#Java life! Go ahead Java,lyf,fly,luf,loof");

while(mt.find()) {
    System.out.println(mt.group());
}

It does not show anything. tried it also, Pattern pt = Pattern.compile("l.+?f{3}");o / p was still not expected.

The o / p value should be:

lyf luf

+4
source share
2 answers

Required Regular Expression

\bl\wf\b

Explanation:

Since your word should be three characters long, this means that there can only be one letter between l and f, so I did not put a quantifier there.

Your regex is wrong because

  • f{3} means 3 f, not 3 characters in total
  • .matches all, including characters without words. Use instead \w.
+2

\b, l, \w, f, \b.

\bl\wf\b

  • \b
  • l
  • \w (\ w - , ASCII [A-Za-z0-9_])
  • a f
  • \b

+3

Source: https://habr.com/ru/post/1690889/


All Articles