Java – how to terminate matcher Find() when it runs too long?

I want to know the technology of terminating long-running regular expression matching (Java matcher. Find () method) Maybe inherit matcher and add some logic after X iterations to terminate?

Basically, I use genetic algorithm to generate regular expressions, so I don't have much control over them Then I test each text against some text to see if they match a target area of the text

Because I generated these regular expressions a little randomly, I got some crazy things. It ate a lot of CPU and some find () calls, which took a while to terminate I'd rather kill them after a while, but I'm not sure the best way

If anyone has an idea, please let me know

Solution

There is a solution here that can solve your problem That question is the same as yours

In essence, it is a charsequence that can notice thread interrupts

Code of the answer:

/**
 * CharSequence that noticed thread interrupts -- as might be necessary 
 * to recover from a loose regex on unexpected challenging input. 
 * 
 * @author gojomo
 */
public class InterruptibleCharSequence implements CharSequence {
    CharSequence inner;
    // public long counter = 0; 

    public InterruptibleCharSequence(CharSequence inner) {
        super();
        this.inner = inner;
    }

    public char charAt(int index) {
        if (Thread.interrupted()) { // clears flag if set
            throw new RuntimeException(new InterruptedException());
        }
        // counter++;
        return inner.charAt(index);
    }

    public int length() {
        return inner.length();
    }

    public CharSequence subSequence(int start,int end) {
        return new InterruptibleCharSequence(inner.subSequence(start,end));
    }

    @Override
    public String toString() {
        return inner.toString();
    }
}

With this wrapped string, you can break the thread

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>