import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?P<hostname>[\\w-_]+)\\s+(?P<localInterface>[A-Za-z]+\\d+(?:\\/\\d+)*)\\s+(?P<holdTime>\\d+)\\s+(?P<capabilities>[A-Z]+)\\s+(?P<remoteInterface>[A-Za-z]+\\d+(?:\\/\\d+)*) ";
final String string = "sh cdp nei\n\n"
+ "Capability Codes: R - Router, T - Trans-Bridge, B - Source-Route-Bridge\n"
+ " S - Switch, H - Host, I - IGMP, r - Repeater,\n"
+ " V - VoIP-Phone, D - Remotely-Managed-Device,\n"
+ " s - Supports-STP-Dispute\n\n"
+ "Device-ID Local Intrfce Hldtme Capability Platform Port ID\n"
+ "CHOD-MGMT-STACK.mhmp\n"
+ " mgmt0 129 S I WS-C2960X-48T Gig1/0/25 \n"
+ "SPINE-401(FDO22041YMP)\n"
+ " Eth1/49 153 R S s N9K-C9336PQ Eth1/36 \n"
+ "SPINE-402(FDO22081W5Y)\n"
+ " Eth1/50 176 R S s N9K-C9336PQ Eth1/36 \n"
+ "IPN-2-CH(FDO221610MG)\n"
+ " Eth1/51 125 R S s N9K-C93180YC- Eth1/51 \n"
+ "IPN-2-CH(FDO221610MG)\n"
+ " Eth1/52 125 R S s N9K-C93180YC- Eth1/52 \n"
+ "IPN-1-KCP(FDO22152M53)\n"
+ " Eth1/54 143 R S s N9K-C93180YC- Eth1/54 \n\n"
+ "Total entries displayed: 6\n\n"
+ "IPN-1-CH# sh lldp nei\n\n"
+ "Capability codes:\n"
+ " (R) Router, (B) Bridge, (T) Telephone, (C) DOCSIS Cable Device\n"
+ " (W) WLAN Access Point, (P) Repeater, (S) Station, (O) Other\n"
+ "Device ID Local Intf Hold-time Capability Port ID \n"
+ "SPINE-401 Eth1/49 120 BR Eth1/36 \n"
+ "SPINE-402 Eth1/50 120 BR Eth1/36 \n"
+ "IPN-2-CH Eth1/51 120 BR Ethernet1/51 \n"
+ "IPN-2-CH Eth1/52 120 BR Ethernet1/52 \n"
+ "IPN-1-KCP Eth1/54 120 BR Ethernet1/54 \n"
+ "Total entries displayed: 5";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
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