2017-04-24 6 views
1

を使用して、文字列に複数の引数をマッチング:は、私は、次のしていることを文字列とし、正規表現

mystr = """ 
<p>Some text and another text. </p> ![image_file_1][image_desc_1] some other text. 
<p>some text</p> 
![image_file_2][image_desc_2] and image: ![image_file_3][image_desc_3] 
test case 1: ![dont_match_1] 
test case 2: [dont_match_2][dont_match_3] 
finally: ![image_file_4][image_desc_4] 
""" 

は私が得ることができるがimage_file_X年代次のコードを使用して:私はimage_desc_Xキャプチャしたい

import re 
re.findall('(?<=!\[)[^]]+(?=\]\[.*?\])', mystr) 

年代を以下は動作しません:

re.findall('(?!\[.*?\]\[)[^]]+(?=\])', mystr) 

お勧めはありますか?私がimage_fileimage_descの両方を得ることができれば、もっと良いだろう1つのコマンドを使うことができます。

答えて

2

使用して、次のアプローチ:

result = re.findall(r'!\[([^]]+)\]\[([^]]+)\]', mystr) 
print(result) 

出力:

[('image_file_1', 'image_desc_1'), ('image_file_2', 'image_desc_2'), ('image_file_3', 'image_desc_3'), ('image_file_4', 'image_desc_4')] 
+1

'の存在を表現する!'正の後読みをする必要はありません。リテラル '!'で十分です。 – revo

1

私はあなたが使用することができます推測:

for match in re.finditer(r"!\[(.*?)\]\[(.*?)]", mystr): 
    print match.group(1) 
    print match.group(2) 

出力:

image_file_1 
image_desc_1 
image_file_2 
image_desc_2 
image_file_3 
image_desc_3 
image_file_4 
image_desc_4 

DEMO

+0

大文字と小文字を区別しないフラグをここで設定する必要がありますか? – revo

+0

これは、デフォルトで来た...私はそれを削除するつもり! –

関連する問題