2016-05-04 5 views
1

と一致するように、一つだけの式ゲット:今すぐPythonの正規表現:だから私は1つの文に対して複数の正規表現に一致するプログラムと格闘してい

import re 

line = "Remind me to pick coffee up at Autostrada at 4:00 PM" 

matchObj = re.match(r'Remind me to (.*) at (.*?) at (.*?) .*', line, re.M|re.I|re.M) 
matchObj2 = re.match(r'Remind me to (.*) at (.*?) .*', line, re.M|re.I) 

if matchObj: 
    print("matchObj.group() : ", matchObj.group()) 
    print("matchObj.group(1) : ", matchObj.group(1)) 
    print("matchObj.group(2) : ", matchObj.group(2)) 
    print("matchObj.group(3) :", matchObj.group(3)) 
else: 
    print("No match!!") 
if matchObj2: 
    print("matchObj2.group() : ", matchObj2.group()) 
    print("matchObj2.group(1) : ", matchObj2.group(1)) 
    print("matchObj2.group(2) : ", matchObj2.group(2)) 
else: 
    print("No match!!") 

を、私は次のように、一度に一致する唯一の正規表現をしたいですこの:

matchObj.group() : Remind me to pick coffee up at Autostrada at 4:00 PM 
matchObj.group(1) : pick coffee up 
matchObj.group(2) : Autostrada 
matchObj.group(3) : 4:00 

は代わりに、両方の正規表現は、このように、ステートメントに一致:

matchObj.group() : Remind me to pick coffee up at Autostrada at 4:00 PM 
matchObj.group(1) : pick coffee up 
matchObj.group(2) : Autostrada 
matchObj.group(3) : 4:00 
matchObj2.group() : Remind me to pick coffee up at Autostrada at 4:00 PM 
matchObj2.group(1) : pick coffee up at Autostrada 
matchObj2.group(2) : 4:00 

matchObjのみがここで適切に一致するはずです。他の正規表現がマッチを報告するのを止めるにはどうすればよいですか?

+0

まさかを。 '。*'非常に貪欲なパターンがある。あなたは、このシナリオの制限規則を思い付くまで、あなたを助ける方法はありません。 d欲張りのトークン、['^私に(?:(?! (*)$)](https://regex101.com/r/vE4oE2/1)でも、それがあなたのために働くかどうかは分かりません。 –

答えて

1

問題は、最初の正規表現にマッチするすべての文字列も(も.*に一致するat (.*?) .*一致するものを第二1と一致していることである。だから、matchObj2 が実際に適切な試合です。

あなたはこれら二つを区別したい場合状況は、あなたがし、最初に一致を生成しない場合にのみ場合は、2番目の正規表現を適用する必要がありません。

import re 

line = "Remind me to pick coffee up at Autostrada at 4:00 PM" 

matchObj = re.match(r'Remind me to (.*) at (.*?) at (.*?) .*', line, re.M|re.I|re.M) 
matchObj2 = re.match(r'Remind me to (.*) at (.*?) .*', line, re.M|re.I) 

if matchObj: 
    print("matchObj.group() : ", matchObj.group()) 
    print("matchObj.group(1) : ", matchObj.group(1)) 
    print("matchObj.group(2) : ", matchObj.group(2)) 
    print("matchObj.group(3) :", matchObj.group(3)) 
elif matchObj2: 
    print("matchObj2.group() : ", matchObj2.group()) 
    print("matchObj2.group(1) : ", matchObj2.group(1)) 
    print("matchObj2.group(2) : ", matchObj2.group(2)) 
else: 
    print("No match!!") 
+0

魅力的な作品です。返事が遅れて申し訳ありません。ありがとう、トン! –