开发者

How do I figure out which regular expression matches my string?

开发者 https://www.devze.com 2023-02-15 16:11 出处:网络
I have 10 regular expressions and 1 one string which may or may not match exactly one of those 10 regular expressions. Does anyone know of a simple way to figure out which regular expression, if any,

I have 10 regular expressions and 1 one string which may or may not match exactly one of those 10 regular expressions. Does anyone know of a simple way to figure out which regular expression, if any, matches my string? I know that I can simply test each one against the string but I'd like to know if there's a library out there that I can input the regular expressions and the string and it'l开发者_如何学Gol tell me if any of my regular expressions match. I need to know which regular expression is matched because the resulting business logic is different for each regular expression.


Here's the API you're looking for. Just invoke it for each of the 10 expressions!

public boolean testMatch(String data, String regEx) {
    return data.matches(regEx);
}

Let's make it more generic.

public String testMatch(String data, String... regExs) {
    for(String regEx : regExs) {
        if(data.matches(regEx)) {
            return regEx;
        }
    }

    return null;
}


Try this out:

String charsequence = "Whatever";
List<Pattern> patterns = null/* Place here all your RegExp*/;

Matcher matcher = null;
for (Pattern p: patterns) {
    matcher = p.matcher(charsequence);
    if (matcher.matches()) {
        // It matches, do stuff
        break;
    }
}

Hope it helps.

Regards


Seeing that you are going to have different logic based on which expression matches. I don't think you can avoid looping through each option (or having another class loop through each option).

You could create classes that have the regular expression and the action to preform and pass the String to that class and let it preform the action if it matches rather than determine a match and have some switch like structure determine the action to preform.

0

精彩评论

暂无评论...
验证码 换一张
取 消