Reputation: 298
i've this line
15815 (sh): demand=3000000 boost=1 reason=0 sync=0 need_idle=0 flags=80002 grp=0 best_cpu=6 latency=0
i want to extract sh and flags value with named backreference using python regex, but always landing up with a None type object, how do i do that?
Below is code for what i tried:
pattern = re.compile(r"\((?P<thread>.*?)\)*\sflags=(?P<flags>\d+)")
m = pattern.search(str)
m.group()
'(sh): demand=3000000 boost=1 reason=0 sync=0 need_idle=0 flags=80002'
Upvotes: 0
Views: 56
Reputation: 626747
You need to match any chars other than (
and )
to match what is inside (...)
and then use .*
or .*?
to match up to the flags
. Then, all you need is to use group("thread")
and group("flags")
to access these values:
import re
s =' 15815 (sh): demand=3000000 boost=1 reason=0 sync=0 need_idle=0 flags=80002 grp=0 best_cpu=6 latency=0'
pattern = re.compile(r"\((?P<thread>[^()]*)\).*?\bflags=(?P<flags>\d+)")
m = pattern.search(s)
print(m.group("thread")) # => sh
print(m.group("flags")) # => 80002
See the Python demo
Note I added a word boundary \b
before flags=
to match flags
as a whole word.
Upvotes: 1