A friend gave me this piece of code and said there is a bug. And yes, this code runs for ever.
The answer I got is:
It runs for >10^15 years before printing anything.
public class Match {
public static void main(String[] args) {
Pattern p = Pattern.compile("(aa|aab?)+");
int count = 0;
for(String s = ""; s.length() < 200; s += "a")
if (p.matcher(s).matches())
count++;
System.out.println(count);
}
}
I didn’t really understand why am I seeing this behavior, I am new to java, do you have any suggestions?
The pattern you are using is known as an evil regex according to OWASP (they know what they’re talking about most of the time):
https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS
It basically matches
aaORaaoraab(since the b is optional by addition of?)A Regex like this is vulnerable to a ReDoS or Regex Denial of Service Attack.
So yes, sort out what you want to match. I suggest in the above example you should simply match
aa, no need for groups, repitition or alternation:Also as someone pointed out, who now deleted his post, you should not use += to append to strings. You should use a StringBuffer instead: