Java regex look-behind group does not have obvious maximum length error

前端 未结 4 2068
情书的邮戳
情书的邮戳 2021-01-05 03:56

I know that java regex does not support varying length look-behinds, and that the following should cause an error

(?<=(not exceeding|no((\\\\w|\\\\s)*)mor         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 04:21

    Below are some test cases (I removed the redundant parens, as mentioned by @Pshemo). It only fails where the lookbehind contains a sub-alternation. The error is

    Look-behind group does not have an obvious maximum length near index 45
    

    "Obvious" being the keyword here.

       import  java.util.regex.Pattern;
    public class Test  {
       public static final void main(String[] ignored)  {
          test("(?<=not exceeding|no)xxxx");
          test("(?<=not exceeding|NOT EXCEEDING)xxxx");
          test("(?<=not exceeding|x{13})xxxx");
          test("(?<=not exceeding|x{12}x)xxxx");
          test("(?<=not exceeding|(x|y){12}x)xxxx");
          test("(?<=not exceeding|no(\\w|\\s){2,30}more than)xxxx");
          test("(?<=not exceeding|no(\\w|\\s){0,2}more than)xxxx");
          test("(?<=not exceeding|no(\\w|\\s){2}more than)xxxx");
       }
          private static final void test(String regex)  {
             System.out.print("testing \"" + regex + "\"...");
             try  {
                Pattern p = Pattern.compile(regex);
                System.out.println("Success");
             }  catch(Exception x)  {
                System.out.println(x);
             }
    
          }
    }
    

    Output:

    testing "(?<=not exceeding|no)xxxx"...Success
    testing "(?<=not exceeding|NOT EXCEEDING)xxxx"...Success
    testing "(?<=not exceeding|x{13})xxxx"...Success
    testing "(?<=not exceeding|x{12}x)xxxx"...Success
    testing "(?<=not exceeding|(x|y){12}x)xxxx"...java.util.regex.PatternSyntaxException: Look-behind group does not
     have an obvious maximum length near index 27
    (?<=not exceeding|(x|y){12}x)xxxx
                               ^
    testing "(?<=not exceeding|no(\w|\s){2,30}more than)xxxx"...java.util.regex.PatternSyntaxException: Look-behind
    group does not have an obvious maximum length near index 41
    (?<=not exceeding|no(\w|\s){2,30}more than)xxxx
                                             ^
    testing "(?<=not exceeding|no(\w|\s){0,2}more than)xxxx"...java.util.regex.PatternSyntaxException: Look-behind g
    roup does not have an obvious maximum length near index 40
    (?<=not exceeding|no(\w|\s){0,2}more than)xxxx
                                            ^
    testing "(?<=not exceeding|no(\w|\s){2}more than)xxxx"...java.util.regex.PatternSyntaxException: Look-behind gro
    up does not have an obvious maximum length near index 38
    (?<=not exceeding|no(\w|\s){2}more than)xxxx
                                          ^
    

提交回复
热议问题