It's a regular question!

Asked 1 years ago, Updated 1 years ago, 90 views

You only want to find the values 10.200.180.2, 10.200.180.3 in the text below. The problem is that IP information should only be selected if there is MAC information before it, such as 64:16:8d:dc:6c:40. So I can find 64:16:8d:dc:6c:40 10.200.180.2, 00:02:a5:74:9b:19 10.200.180.3 in the regular expression below, but can I print only IP information from the target I found? I can't find a way to deal with this as a regular expression"T" [A-Za-z0-9][A-Za-z0-9][:][A-Za-z0-9][A-Za-z0-9][:][A-Za-z0-9][A-Za-z0-9][:][A-Za-z0-9][A-Za-z0-9][:][A-Za-z0-9][A-Za-z0-9][:][A-Za-z0-9]A-Za-z0-9{3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])

admin@Test_M7i# show | compare [edit interfaces fe-1/3/0 unit 0 family inet address 10.200.180.1/24]

admin@Test_M7i> show arp no-resolve MAC Address Address Interface Flags 64:16:8d:dc:6c:40 10.200.180.2 fe-1/3/0.0 none 00:02:a5:74:9b:19 10.200.180.3 fe-1/3/0.0 permanent

regex

2022-09-22 21:42

2 Answers

Here's how the Java version works:

import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class MyRegex{
    public static void main(String[] args){
        String searchTarget = "64:16:8d:dc:6c:40 10.200.180.2, 00:02:a5:74:9b:19 10.200.180.3 10.200.180.5 10.200.180.6";

        Pattern pattern = Pattern.compile("[0-9a-e]{2}\\:[0-9a-e]{2}\\:[0-9a-e]{2}\\:[0-9a-e]{2}\\:[0-9a-e]{2}\\:[0-9a-e]{2}\\s(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})");
        Matcher matcher = pattern.matcher(searchTarget);
        while(matcher.find()){
            System.out.println(matcher.group(1));
        }
    }
}

For your information, Java should be written twice, such as \ for escape.


2022-09-22 21:42

You can use something called a capturing group.

The bottom is the Python code. Find the ip in search_target and print it out. When you look at regex, only the subsequent ip is found if there is a previous MAC address based on \s.

regex = r'[0-9a-e]{2}\:[0-9a-e]{2}\:[0-9a-e]{2}\:[0-9a-e]{2}\:[0-9a-e]{2}\:[0-9a-e]{2}\s(?P<url>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'

search_target = "64:16:8d:dc:6c:40 10.200.180.2, 00:02:a5:74:9b:19 10.200.180.3 10.200.180.5 10.200.180.6"

import re
result = re.findall(regex, search_target)
print("\n".join(result))

You can run it yourself by pressing the Run button at the bottom of the code above.


2022-09-22 21:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.