PSSGCSim
PSSGCSim

Reputation: 1287

Regex with exception

i need regex for detect all IPs with ports and without ports but excepting

93.153.31.151(:27002)

and

10.0.0.1(:27002)

I have got some but I need add exception

\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d{1,5})?

For java matcher

    String numIPRegex = "\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d{1,5})?";

    if (pA.matcher(msgText).find()) {
        this.logger.info("Found");

    } else {    
        this.logger.info("Not Found");                  

    }

Upvotes: 1

Views: 179

Answers (2)

Tomalak
Tomalak

Reputation: 338218

Without making a statement about better-suited Java classes that can handle IP addreses in a structured manner...

You can add exceptions to a regular expression using negative look-aheads:

String numIPRegex = "(?!(?:93\\.153\\.31\\.151|10\\.0\\.0\\.1)(?::27002)?)\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d{1,5})?";

Explanation:

(?!                                   # start negative look-ahead
  (?:                                 #   start non-capturing group
    93\.153\.31\.151                  #     exception address #1
    |                                 #     or
    10\.0\.0\.1                       #     exception address #2
  )                                   #   end non-capturing group
  (?:                                 #   start non-capturing group
    :27002                            #     port number
  )?                                  #   end non-capturing group; optional
)                                     # end negative look-ahead
\d{1,3}(?:\.\d{1,3}){3}(?::\d{1,5})?  # your original expression

Of course the other obvious alternative would be to test the exceptions up-front one by one and just return false if one exceptions matches. Wrapping them up all up in one single big regex will quickly become very ugly.

Upvotes: 4

ggrandes
ggrandes

Reputation: 2133

You want this?

public static void main(String[] args) {
    System.out.println(match("93.153.31.151(:27002)")); // false
    System.out.println(match("12.23.34.45(:21002)")); // true
}
public static boolean match(String input) {
    String exclude = "|93.153.31.151(:27002)|10.0.0.1(:27002)|";
    if (exclude.contains("|" + input + "|")) return false; // Exclude from match
    //
    String numIPRegex = "^\\d{1,3}(\\.\\d{1,3}){3}\\(:\\d{1,5}\\)$";
    Pattern pA = Pattern.compile(numIPRegex);
    //
    if (pA.matcher(input).matches()) {
        System.out.println("Found");
        return true;
    } else {    
        System.out.println("Not Found");                  
    }
    return false;
}

Upvotes: 0

Related Questions