2017-04-20 1 views
1

私はこのような複数の文字列を持っています。 product: green apples price: 2.0 country: france company: somecompanyです。いくつかの文字列ではフィールドが少なくなる場合があります。たとえば、会社名や国などが見つからないものがあります。私は値を抽出し、製品、価格、国、会社をスキップしようとしています。私は各文字列の左側から始まる複数の正規表現を作成しようとしました。Pythonの文字列から複数の値を正規表現で抽出する

blah="product: green apples price: 2.0 country: france company: somecompany" 

product_reg = re.compile(r'.*?\bproduct\b:(.*).*') 
product_reg_strip = re.compile(r'(.*?)\s[a-z]:?') 

product_full=re.findall(product_reg, blah) 
prod=re.find(product_reg_strip, str(product_full)) 
print prod 

price_reg = re.compile(r'.*?\bprice\b:(.*).*') 
price_reg_strip = re.compile(r'(.*?)\s[a-z]:?') 

price_full=re.findall(price_reg, blah) 
price=re.find(price_reg_strip, str(price_full)) 
print price 

しかし、これは機能しません。この正規表現をもっと正気にするために私は何をすべきですか?

+0

価格は各文字列の唯一の数値ですか? –

+0

出力をどのようにしたいですか?あなたの例では、 'green apples 2.0 france somecompany'ですか? – tdelaney

答えて

0

あなたはそのような文字列を分割することができます:

str = "product: green apples price: 2.0 country: france company: somecompany" 
p = re.compile(r'(\w+:)') 
res = p.split(str) 
print res 
for i in range(len(res)): 
    if (i%2): 
     print res[i],' ==> ',res[i+1] 

出力:

['', 'product:', ' green apples ', 'price:', ' 2.0 ', 'country:', ' france ', 'company:', ' somecompany'] 

product: ==> green apples 
price: ==> 2.0 
country: ==> france 
company: ==> somecompany 
0

私はあなたが後にあるか、完全にわからないんだけど、物事はあなたが削除する場合あり1つの単語の後にコロンが続く場合、正規表現はかなり簡単です。ここにいくつかのサンプルがあります。

>>> import re 
>>> blah="product: green apples price: 2.0 country: france company: somecompany" 
>>> re.sub(r'\w+: ?', '', blah) 
'green apples 2.0 france somecompany' 
>>> re.split(r'\w+: ?', blah)[1:] 
['green apples ', '2.0 ', 'france ', 'somecompany'] 
0

単純にregexpを使用して、名前付きグループ結果を取得することができます。 あなたが尋ねたとおりにすべての値を持つこともできないこともありますが、正規表現はすべての場合にうまく機能します。 regex101.com https://regex101.com/r/iccVUv/1/にこのグローバル複数行の正規表現を使用してみてください:

たとえば行うことができますPythonで
^(?:product:(?P<product>.*?))(?:price:(?P<price>.*?))?(?:country:(?P<country>.*?))?(?:company:(?P<company>.*))?$ 

、この:単純に使用して

pattern = '^(?:product:(?P<product>.*?))(?:price:(?P<price>.*?))?(?:country:(?P<country>.*?))?(?:company:(?P<company>.*))?$' 
matches = re.search(pattern, 'product: green apples price: 2.0 country: italy company: italian company') 

今、あなたが得ることができるデータ:

product = matches.group('product') 

最終的には、一致が満足されているかどうかを確認し、次のような空白を削除する必要があります。

if matches1.group('product') is not None: 
    product = matches.group('product').strip() 
関連する問題