Ajax
Ajax

Reputation: 179

Extract digits using multi condition regex in paragraphs in python

I have this text in .txt files:

crt - 00:00:00 up 200 days, 23:35, 0 users, load average: 0.04, 0.05, 0.02
Tasks: 300 total, 2 running, 298 sleeping, 0 stopped, 0 zombie
Cpu(s): 12.0%us, 2.5%sy, 0.0%ni, 89.2%id, 0.0%hi, 0.1%si, 0.0%st
Mem: 123456K total, 1234567k used, 989991k free, 11156793k buffers
Swap: 456K total, 30897564k used, 785431k free, 23445897k cached

PID User Pr NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
24 455  36  63  700 800 900 456 87 35 46
2 root 80 0 0 0 0 0 0 0 0 0 0 0 0 0 0 thread

crt - 00:00:04 up 200 days, 23:39, 0 users, load average: 0.04, 0.05, 0.02
Tasks: 300 total, 2 running, 298 sleeping, 0 stopped, 0 zombie
Cpu(s): 12.0%us, 2.5%sy, 0.0%ni, 89.2%id, 0.0%hi, 0.1%si, 0.0%st
Mem: 123456K total, 1234567k used, 989991k free, 11156793k buffers
Swap: 456K total, 30897564k used, 785431k free, 23445897k cached

I want all the digit values in all paragraphs between crt and cachedexcluding the values between PID and thread. Till now i am using this:

regex.findall(r'(?<!\d)(?<=\bcrt\b.*?)(?:\d{2}:\d{2}(?::\d{2})?|\d*\.?\d+)(?!\d)(?=.*\bcached\b)', text, regex.S)

But this gives all digits including between PID and thread. Any Ideas?

Upvotes: 1

Views: 35

Answers (1)

Jan
Jan

Reputation: 43169

Since you're already using the regex module (which supports a variable lookbehind), you could easily use \G and \K as well:

(?:^crt|\G(?!\A))(?:(?!^$)\D)*\K[.:\d]+

See a demo on regex101.com.


Broken down, this assumes a couple of things:
(?:
    ^crt        # start a line with crt
    |           # or 
    \G(?!\A)    # start after thre previous match (unless it is the very start of the string)
)
(?:(?!^$)\D)*\K # match any non-digit character, but stop at empty lines
[.:\d]+         # character class with ., : and digits

In Python the code could be:

import regex as re

junk = """
crt - 00:00:00 up 200 days, 23:35, 0 users, load average: 0.04, 0.05, 0.02
Tasks: 300 total, 2 running, 298 sleeping, 0 stopped, 0 zombie
Cpu(s): 12.0%us, 2.5%sy, 0.0%ni, 89.2%id, 0.0%hi, 0.1%si, 0.0%st
Mem: 123456K total, 1234567k used, 989991k free, 11156793k buffers
Swap: 456K total, 30897564k used, 785431k free, 23445897k cached

PID User Pr NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
24 455  36  63  700 800 900 456 87 35 46
2 root 80 0 0 0 0 0 0 0 0 0 0 0 0 0 0 thread

crt - 00:00:04 up 200 days, 23:39, 0 users, load average: 0.04, 0.05, 0.02
Tasks: 300 total, 2 running, 298 sleeping, 0 stopped, 0 zombie
Cpu(s): 12.0%us, 2.5%sy, 0.0%ni, 89.2%id, 0.0%hi, 0.1%si, 0.0%st
Mem: 123456K total, 1234567k used, 989991k free, 11156793k buffers
Swap: 456K total, 30897564k used, 785431k free, 23445897k cached
"""

rx = re.compile(r'(?:^crt|\G(?!\A))(?:(?!^$)\D)*\K[.:\d]+', re.M)

for match in rx.finditer(junk):
    print(match.group(0))

Which yields (abbreviated):

00:00:00
200
23:35
...

Upvotes: 1

Related Questions