regex - how to print previous string after selecting specific string python -
i want find word appear before keyword (specified , searched me) , print out result. tried below code gives me after words not before...
str = "phone has better display, speaker. phone has average display" p1 = re.search(r"(display>=?)(.*)", str) if p1 none: return none return p1.groups()
this code gives me
, speaker. phone has average display
but want
better,average
you can use positive lookahead, findall
instead of search
:
>>> p = re.compile(r'(\w+)\s+(?=display)') >>> p.findall(str) ['better', 'average']
Comments
Post a Comment