Extract string and assign to the variable using regex in Python

Mark765

I am trying to write a script which will go through text file and check for particular content and assign to the variable.

For example:

Text file content:

eth0      Link encap:Ethernet  HWaddr 08:ee:27:ff:b3:d7  
          inet addr:10.0.2.45  Bcast:10.3.2.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fe00:b3d7/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:16178 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8559 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:14045795 (14.0 MB)  TX bytes:1355632 (1.3 MB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:666 errors:0 dropped:0 overruns:0 frame:0
          TX packets:666 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:72748 (72.7 KB)  TX bytes:72748 (72.7 KB)

I would like to check value of 'RX packets' on interface eth0 and assign value '16178' to the variable. I need to be able to extract this value from this particular block 'eth0'.

Please advise where to start?

Thank you.

user4179775

You can use regular expression to extract the value.

Try a pattern:

m = re.match("\W*RX packets[^:]*:(\d+)", line)

In a regular expression \d means a digit, and a + means one or more. You want to 'match' one or more numbers in the text. The brackets mean to capture what is found into a number, this number should be found after a specific text RX packets:.

You can find more details about regular expression in the official doc.

Your code would look like:

data= """
eth0      Link encap:Ethernet  HWaddr 08:ee:27:ff:b3:d7  
          inet addr:10.0.2.45  Bcast:10.3.2.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fe00:b3d7/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:16178 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8559 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:14045795 (14.0 MB)  TX bytes:1355632 (1.3 MB)

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:666 errors:0 dropped:0 overruns:0 frame:0
          TX packets:666 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:72748 (72.7 KB)  TX bytes:72748 (72.7 KB)"""

import re

def findSeq(block,data):
    isInRightBlock= False
    for line in data.splitlines():
        if block in line:
            isInRightBlock= True
        m = re.match("\W*RX packets[^:]*:(\d+)", line)
        if m and isInRightBlock:
            isInRightBlock= False
            return m.group(1)


res= findSeq("eth0",data)
print res #Your Value

Output:

16178

Banchemark

from datetime import datetime
start_time_1 = datetime.now()
res= findSeq("eth0",data)
print('Duration: {}'.format(datetime.now() - start_time_1))

from datetime import datetime
start_time_2 = datetime.now()
re.search(r'eth0.*?RX packets:(\d+)',data,re.DOTALL).group(1)
print('Duration: {}'.format(datetime.now() - start_time_2))

Output:

Duration: 0:00:00.000547
Duration: 0:00:00.000344

NT: You can optimize the way it checks the right block.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Extract USD amout at beginning of string using regex

From Dev

Using regex to extract first half of string

From Dev

Need a regex to extract a portion of the string using java

From Dev

Using regex to extract information from string

From Dev

Python - using variable in regex

From Dev

Extract House Number and Street Name from string using Python Regex

From Dev

Extract string from file and assign to variable using scripting in Bash

From Dev

Python - Extract pattern from string using RegEx

From Dev

extract numbers within a string using regex

From Dev

Extract a string from textfile using JS regex

From Dev

Replace multiple variable values in string using Python regex

From Dev

Extract ip address from a string using regex

From Dev

Using regex to extract numbers and symbols from string

From Dev

Python regex to extract a portion of string

From Dev

Python extract occurence of a string with regex

From Dev

javascript regex string template extract variable

From Dev

Extract word from string Using python regex

From Dev

extract and assign matched regex pattern from string in Perl to a variable

From Dev

assign entire column to a string variable using VBA

From Dev

Extract a value from an input of type string and assign to a variable

From Dev

extract string using ruby regex

From Dev

Python - using variable in regex

From Dev

Extract House Number and Street Name from string using Python Regex

From Dev

Python regex extract string multiline

From Dev

Using a variable in a regex in Python

From Dev

Extract text using word VBA regex then save to a variable as string

From Dev

Extract string if found using regex

From Dev

How to extract some words pattern from string using regex in python

From Dev

extract number in string using regex

Related Related

  1. 1

    Extract USD amout at beginning of string using regex

  2. 2

    Using regex to extract first half of string

  3. 3

    Need a regex to extract a portion of the string using java

  4. 4

    Using regex to extract information from string

  5. 5

    Python - using variable in regex

  6. 6

    Extract House Number and Street Name from string using Python Regex

  7. 7

    Extract string from file and assign to variable using scripting in Bash

  8. 8

    Python - Extract pattern from string using RegEx

  9. 9

    extract numbers within a string using regex

  10. 10

    Extract a string from textfile using JS regex

  11. 11

    Replace multiple variable values in string using Python regex

  12. 12

    Extract ip address from a string using regex

  13. 13

    Using regex to extract numbers and symbols from string

  14. 14

    Python regex to extract a portion of string

  15. 15

    Python extract occurence of a string with regex

  16. 16

    javascript regex string template extract variable

  17. 17

    Extract word from string Using python regex

  18. 18

    extract and assign matched regex pattern from string in Perl to a variable

  19. 19

    assign entire column to a string variable using VBA

  20. 20

    Extract a value from an input of type string and assign to a variable

  21. 21

    extract string using ruby regex

  22. 22

    Python - using variable in regex

  23. 23

    Extract House Number and Street Name from string using Python Regex

  24. 24

    Python regex extract string multiline

  25. 25

    Using a variable in a regex in Python

  26. 26

    Extract text using word VBA regex then save to a variable as string

  27. 27

    Extract string if found using regex

  28. 28

    How to extract some words pattern from string using regex in python

  29. 29

    extract number in string using regex

HotTag

Archive