The code you provide is an extremely inefficient way to solve the problem. I would implement the solution using Rabin-Karp or some other hash algorithm that will allow you to solve your problem with O((yx) * L) complexity.
You cannot use regular expressions here - they are designed to solve different problems.
Regarding the question of how to use your solution to find the longest substring with a length between x and y , just change the loop over j to only consider values ββthat are in the interval [x, y] . Here is how you can do it.
for (int j = Math.max(longest.length() + 1, x) ; j * 2 < text.length() - i && j < y; j++)
EDIT: to find the longest substring, undo the for loop:
for (int j = Math.min((text.length() - i -1)/2, y) ; j > longest.length() && j >=x; j--)
source share