Kuldeep Bisen
Kuldeep Bisen

Reputation: 59

How to timeout or skip any matcher(Regular Expression) in java if taking too long time to match?

In my project I'm using regex to match with string. Here String is dynamic so sometime it takes too long time to match string. here is my code (Keywords.p_resumeHeading is pattern object):

for (int k = 0; k < forcheck.length; k++) {
    Matcher m = Keywords.p_resumeHeading.matcher(forcheck[k].trim());
    if (m.find()) {

        //System.out.println("Resume heading hai ");
        finalresult = true;
        break;
    }
}

Upvotes: 1

Views: 1283

Answers (2)

Puce
Puce

Reputation: 38132

You could consider to submit a Runnable to an ExecutorService to start the find operation in another thread and use the returned Future object to specify the maximum time to wait.

You can use the Executors class to create an ExecutorService.

Upvotes: 0

JFPicard
JFPicard

Reputation: 5168

I've got a similar case with a 'malformed' regex. The best way to deal with it is to limit repetition of your groups with {x} where x is a realistic number (5 or 10) maybe will suffice. Check http://www.regular-expressions.info/repeat.html on limiting repetition.

Whitout your regex, I can't help you better.

Upvotes: 1

Related Questions