简体   繁体   English

如何在选择特定的字符串python后打印先前的字符串

[英]how to print previous string after selecting specific string python

I want to find word that appear before a keyword (specified and searched by me) and print out the result. 我想找到出现在关键字之前的单词(由我指定并搜索),然后打印出结果。 I tried below code but it gives me after words not before... 我尝试了下面的代码,但它给了我一些之前没有的话...

    str = "Phone has better display, good speaker. Phone has average display"
    p1 = re.search(r"(display>=?)(.*)", str)
    if p1 is None:
       return None
    return p1.groups()

this code gives me 这段代码给了我

    , good speaker. Phone has average display

but i want only 但我只想要

    better,average

You can use a positive lookahead, with findall instead of search : 您可以使用findall而不是search来进行正向查找:

>>> p = re.compile(r'(\w+)\s+(?=display)')
>>> p.findall(str)
['better', 'average']

You can use a positive lookahead assertion ?= : 您可以使用正向超前断言?=

import re

str = "Phone has better display, good speaker. Phone has average display"
p1 = re.findall(r"(\w+)\s*(?=display)", str)
print(p1)
# ['better', 'average']

\\w means a word character. \\w表示单词字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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