Match a string against multiple regex patterns

前端 未结 6 1370
甜味超标
甜味超标 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:17

    To avoid recreating instances of Pattern and Matcher classes you can create one of each and reuse them. To reuse Matcher class you can use reset(newInput) method. Warning: This approach is not thread safe. Use it only when you can guarantee that only one thread will be able to use this method, otherwise create separate instance of Matcher for each methods call.

    This is one of possible code examples

    private static Matcher m1 = Pattern.compile("regex1").matcher("");
    private static Matcher m2 = Pattern.compile("regex2").matcher("");
    private static Matcher m3 = Pattern.compile("regex3").matcher("");
    
    public boolean matchesAtLeastOneRegex(String input) {
        return     m1.reset(input).matches() 
                || m2.reset(input).matches()
                || m3.reset(input).matches();
    }
    

提交回复
热议问题