简体   繁体   中英

how to search characters between parentheses and search for a named backreference regex python

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM