Cancelling a long running regex match?

后端 未结 7 1762
借酒劲吻你
借酒劲吻你 2020-11-27 04:25

Say I\'m running a service where users can submit a regex to search through lots of data. If the user submits a regex that is very slow (ie. takes minutes for Matcher.find()

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 05:01

    From Heritrix: (crawler.archive.org)

    /**
     * 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();
        }
    }
    

    Wrap your CharSequence with this one and Thread interrupts will work ...

提交回复
热议问题