SHARE
TWEET

Regex Grouping Using The IP Address Example

a guest Feb 24th, 2016 88 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3.  
  4. public class RegexGroupsIPAddress {
  5.     public static void main(String args[]) {
  6.  
  7.         // String to be scanned to find the pattern.
  8.         String line = "123.234.212.97     134.241.99.445";
  9.         String pattern = "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})";
  10.  
  11.         // Create a Pattern object
  12.         Pattern r = Pattern.compile(pattern);
  13.  
  14.         // Now create matcher object.
  15.         Matcher m = r.matcher(line);
  16.         while (m.find()) {
  17.             int bitValue = 0;
  18.             for (int i = 1; i <= 4; i++) {
  19.                 int octet = Integer.parseInt(m.group(i));
  20.                 if (octet >= 0 && octet <= 255) {
  21.                     bitValue = (bitValue << 8) + octet;
  22.                 } else {
  23.                     bitValue = -1;
  24.                     break;
  25.                 }
  26.             }
  27.             if (bitValue >= 0) {
  28.                 System.out.println("Valid IP Address Found: " + m.group(0)
  29.                         + "; BitValue = " + bitValue);
  30.             } else {
  31.                 System.out.println("Illegal IP Address Found: " + m.group(0));
  32.             }
  33.         }
  34.     }
  35. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top