Match a string against multiple regex patterns

前端 未结 6 1377
甜味超标
甜味超标 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条回答
  •  渐次进展
    2020-12-29 05:27

    If you have just a few regexes, and they are all known at compile time, then this can be enough:

    private static final Pattern
      rx1 = Pattern.compile("..."),
      rx2 = Pattern.compile("..."),
      ...;
    
    return rx1.matcher(s).matches() || rx2.matcher(s).matches() || ...;
    

    If there are more of them, or they are loaded at runtime, then use a list of patterns:

    final List rxs = new ArrayList<>();
    
    
    for (Pattern rx : rxs) if (rx.matcher(input).matches()) return true;
    return false;
    

提交回复
热议问题