1

I am making a java IRC lib and I need a method to see if a certain user matches a hostmask which can contain a wildcard * character. What is the simplest way to do this without using regex?

Some examples:

    // Anything works
    *
            server.freenode.net ✔

    // Any nickname/user/host works
    *!*@*:
            any!thing@works ✔

    // Any nickname works (may have multiple nicknames on the same user)
    *!nebkat@unaffiliated/nebkat:
            nebkat!nebkat@unaffiliated/nebkat ✔
            123456!nebkat@unaffiliated/nebkat ✔
            nebkat!nebkat@unaffiliated/hacker ✘

    // Anything from an ip
    *!*@123.45.67.8:
            nebkat!nebkat@123.45.67.8 ✔
            123456!user2@123.45.67.8 ✔
            nebkat!nebkat@87.65.43.21 ✘

    // Anything where the username ends with nebkat
    *!*nebkat@*
            nebkat!nebkat@unaffiliated/nebkat ✔
            nebkat!prefix_nebkat@unaffiliated/nebkat ✔
            nebkat!nebkat_suffix@unaffiliated/nebkat ✘
nebkat
  • 8,445
  • 9
  • 41
  • 60
  • 3
    Why without using regex? This looks like a perfect match for a regex. – Tom Johnson Oct 31 '12 at 11:18
  • @TomJohnson I thought the special characters could interfere and I would have to handle that. Since its only a single wildcard character I thought it would be more simple without regex? – nebkat Oct 31 '12 at 11:59
  • you can always escape special characters... – jlordo Oct 31 '12 at 12:47

2 Answers2

3

Use org.apache.commons.io.FilenameUtils#wildcardMatch() method. More details are in answer https://stackoverflow.com/a/43394347/466677.

Community
  • 1
  • 1
Marek Gregor
  • 3,691
  • 2
  • 26
  • 28
2

Ended up with this:

public static boolean match(String host, String mask) {
    String[] sections = mask.split("\\*");
    String text = host;
    for (String section : sections) {
        int index = text.indexOf(section);
        if (index == -1) {
            return false;
        }
        text = text.substring(index + section.length());
    }
    return true;
}
nebkat
  • 8,445
  • 9
  • 41
  • 60
  • Notice that when `host` is `abcdef` and `mask` is `abc` the answer will still be "true" for that function. – Yonatan Jul 09 '17 at 11:41