Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 选择特定字符串后如何打印上一个字符串_Python_Regex_Search_Keyword_Matching - Fatal编程技术网

Python 选择特定字符串后如何打印上一个字符串

Python 选择特定字符串后如何打印上一个字符串,python,regex,search,keyword,matching,Python,Regex,Search,Keyword,Matching,我想找到出现在关键字之前的单词(由我指定和搜索)并打印出结果。我尝试下面的代码,但它给我的话后,而不是之前 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() 这个密码给了我

我想找到出现在关键字之前的单词(由我指定和搜索)并打印出结果。我尝试下面的代码,但它给我的话后,而不是之前

    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()
这个密码给了我

    , good speaker. Phone has average display
但我只想

    better,average

您可以使用正向前瞻,使用
findall
而不是
search

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

您可以使用正向前瞻断言
?=

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
表示单词字符。

是的,它可以工作。r'(\w+)\s+(?=显示)和r'(\w+)\s*(?=显示)
\s+
:一个或多个空白字符,
\s*
零个或多个空白字符。因此,第一个将不匹配
neodisplay
(因为
display
)而第二个将不匹配。