Java Regex with pattern matcher

  • 0


    Regular Expressions (Regex for short) are nice but their computation can take time. You can reduce that time by using precompiled patterns. That's what I did in this version.

    import java.util.regex.*;
    public class Solution {
        private static final Pattern IPV4 = Pattern.compile("(([1-9]|1\\d|2[0-4])?\\d|25[0-5])(\\.(([1-9]|1\\d|2[0-4])?\\d|25[0-5])){3}");
        private static final Pattern IPV6 = Pattern.compile("([0-9A-Fa-f]{1,4})(:([0-9A-Fa-f]{1,4})){7}");
        public String validIPAddress(String IP) {
            if (IPV4.matcher(IP).matches()) {
                return "IPv4";
            if (IPV6.matcher(IP).matches()) {
                return "IPv6";
            return "Neither";

    Here, (([1-9]|1\\d|2[0-4])?\\d|25[0-5]) matches the numbers from 0 to 255 without leading 0s.

    ([0-9A-Fa-f]{1,4}) matches groups of 1 to 4 hexadecimal digits.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.