Regular expression hangs - Java matcher

后端 未结 2 882
悲&欢浪女
悲&欢浪女 2021-01-23 09:20

String:

Aqua, Sodium Laureth Sulfate, Sodium Lauryl Sulfate, Dimethicone, Cocamide MEA, Zinc Carbonate, Glycol Distearate, Sodium Chloride, Zinc Pyrithion

2条回答
  •  伪装坚强ぢ
    2021-01-23 09:50

    Perhaps what you had in mind was

    String regex = "([A-Z][\\d\\w]+( [A-Z][-\\d\\w]+)*, )*[A-Z][-\\d\\w]+( [A-Z][-\\d\\w]+)*\\.";
    System.out.println(string.matches(regex));
    

    returns true.

    The problem you have with the regex is that its overly complicated. The disadvantage with adding expressions until you get true is that it can match things you didn't have in mind.

    Random rand = new Random();
    while(true) {
        byte[] bytes = new byte[40];
        rand.nextBytes(bytes);
        for (int i = 0; i < bytes.length; i++) bytes[i] &= 0x7F;
        String string = new String(bytes, 0);
        if (string.matches("([\\W]*\\b[A-Z\\d]\\w+\\b[\\W\\d]*)+"))
            System.out.println(string);
    }
    

    prints things such as

    "^;%XX`'SwJ|[*4"*0C7`LHsCN*,{26O}
    EFJ5MBVxi%W_t6v54EmLmgjFvqyYh\<"
    +7]|ULh2[MT`Yx{MKH4N
    '8p!2mf
    

    whereas the expression I gave matches

    KfhBuGv7, S3.
    IWzu, XHop4Z.
    LJbXfrd, PdR.
    V2dxQV, LA9z.
    HKf37cy0, TS.
    RAw2E5a, Ajs.
    Up-, GPQ7 I_.
    

提交回复
热议问题