import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "\\b(\n"
+ " # MAC address like xx:xx:xx:xx:xx:xx\n"
+ " [0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}\n"
+ " |\n"
+ " # MAC address like xx-xx-xx-xx-xx-xx\n"
+ " [0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}\n"
+ " |\n"
+ " # MAC address like xxxx.xxxx.xxxx\n"
+ " [0-9a-f]{4}\\.[0-9a-f]{4}\\.[0-9a-f]{4}\n"
+ " |\n"
+ " # IPv4 address in dotted-quad format\n"
+ " # Not a lot of value for our needs in checking range of each octet\n"
+ " # Need to be more mindful of performance here anyway.\n"
+ " \\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\n"
+ ")\\b";
final String string = "192.168.1.2\n"
+ "10.0.0.0\n"
+ "ff:ff:ff:ff:ff:ff\n"
+ "FF-FF-FF-FF-FF-FF\n"
+ "FFFF.FFFF.FFFF\n"
+ "ffff.ffff.ffff\n"
+ "blah127.0.0.1haha\n"
+ "foo127.0.0.1\n\n\n";
final String subst = "\\1";
final Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.COMMENTS);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceFirst(subst);
System.out.println("Substitution result: " + result);
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html