Match a string against multiple regex patterns

前端 未结 6 1357
甜味超标
甜味超标 2020-12-29 04:46

I have an input string.

I am thinking how to match this string against more than one regular expression effectively.

Example Input: ABCD
6条回答
  •  萌比男神i
    2020-12-29 05:15

    I'm not sure what effectively means, but if it's about performance and you want to check a lot of strings, I'd go for this

    ...
    static Pattern p1 = Pattern.compile("[a-zA-Z]{3}");
    static Pattern p2 = Pattern.compile("^[^\\d].*");
    static Pattern p3 = Pattern.compile("([\\w&&[^b]])*");
    
    public static boolean test(String s){
       return p1.matcher(s).matches ? true: 
            p2.matcher(s).matches ? true: 
            p3.matcher(s).matches;
    }
    

    I'm not sure how it will affect performance, but combining them all in one regexp with | could also help.

提交回复
热议问题