2016-05-28 40 views
1

キーワードの前に出現する単語を検索し、その結果を印刷したいと考えています。私は、コードの下にしようとしたが、それは前の単語の後に私をない与える...特定の文字列を選択して前の文字列を印刷する方法python

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 

答えて

2

をしたいです、searchの代わりにfindallである。

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

はい、動作します。 – Vivek

+0

'\ s +':1つ以上の空白文字、 '\ s *'ゼロ(0 = 0)またはそれ以上の空白文字。したがって、最初のものは 'neodisplay'にマッチしません(' display'の前に空白がないので)。 –

0

あなたは肯定先読みアサーション?=使用することができます。

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を単語文字を意味します。

関連する問題