Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract the characters I need from a multiline string

I need to display the ip address after address: . Everything else needs to be trimmed. What code will most optimally solve my problem?

show interface PPPoE0

               id: PPPoE0
            index: 0
             type: PPPoE
      description: Internet (NetFriend)
   interface-name: PPPoE0
             link: up
        connected: yes
            state: up
              mtu: 1400
         tx-queue: 1000
          address: 46.42.50.121
             mask: 255.255.255.255
           global: yes
        defaultgw: yes
         priority: 1000
   security-level: public
        auth-type: PAP, CHAP, MS-CHAP, MS-CHAPv2
           remote: 46.42.48.1
           uptime: 45562
       session-id: 23430
             fail: no
              via: GigabitEthernet0/Vlan2
      last-change: 45562.183918

(config)> exit
Core::Configurator: Bye.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use a simple Regular Expression to search for all matching IPs in a string.

The regex query for an IP Adress would be : (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})
If you want to learn what the RegEx query does you can see the full explanation here.

The code would look something like

import re

text = """
        show interface PPPoE0
    
                   id: PPPoE0
                index: 0
                 type: PPPoE
          description: Internet (NetFriend)
       interface-name: PPPoE0
                 link: up
            connected: yes
                state: up
                  mtu: 1400
             tx-queue: 1000
              address: 46.42.50.121
                 mask: 255.255.255.255
..................
"""

regex_pattern_ip = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')

ip = regex_pattern_ip.search(text)[0]

print(ip)

Hope this helped

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading