2012-05-21 5 views
2

J'ai un code python comme ci-dessous: Ma question est pourquoi la variable appariée est ['']? (Je l'regex dans regexpal.com, il peut trouver le bon résultat |. Name = A Johnson | toto)pourquoi cette regex ne peut pas trouver le résultat

import re 
a = 
'{{Infobox U.S. Cabinet |align=left |clear=yes |Name=A. Johnson |President=Andrew Johnson |President start=1865 |President end=1869 |Vice President=None |Vice President start=1865 |Vice President end=1869 |State=[[William H. Seward]] |State start=1865 |State end=1869 |War=[[Edwin M. Stanton]] |War start=1865 |War end=1868 |War 2=[[John Schofield|John M. Schofield]] |War start 2=1868 |War end 2=1869 |Treasury=[[Hugh McCulloch]] |Treasury start=1865 |Treasury end=1869 |Justice=[[James Speed]] |Justice start=1865 |Justice end=1866 |Justice 2=[[Henry Stanberry]] |Justice start 2=1866 |Justice end 2=1868 |Justice 3=[[William M. Evarts]] |Justice start 3=1868 |Justice end 3=1869 |Post=[[William Dennison (Ohio governor)|William Dennison]] |Post start=1865 |Post end=1866 |Post 2=[[Alexander Randall|Alexander W. Randall]] |Post start 2=1866 |Post end 2=1869 |Navy=[[Gideon Welles]] |Navy start=1865 |Navy end=1869 |Interior=[[John P. Usher]] |Interior date=1865 |Interior 2=[[James Harlan (senator)|James Harlan]] |Interior start 2=1865 |Interior end 2=1866 |Interior 3=[[Orville H. Browning]] |Interior start 3=1866 |Interior end 3=1869 }}' 
matched = re.findall("\|?\s*name\s*=(.)*?\|",a,re.I) 
+0

Je vois pourquoi le résultat est différent de python et regexpal.com. L'expression rationnelle de Python traitera() différemment des autres. le() de findall dans python retournera le matériel dans(), pas dans son ensemble. Alors changez simplement \ |? \ S * nom \ s * = (.) *? \ | à \ |? \ s * nom \ s * =. *? \ | peut résoudre le problème –

Répondre

3

Vous voulez (.*?), pas (.)*? -le dernier (ce que vous avez) sera seulement capture un seul caractère, même si en consomme plus d'une seule. Un groupe de capture ne sera retourné qu'une seule fois même si le groupe lui-même a une répétition; donc ce dernier capture un seul caractère (.) malgré sa répétition.

Si vous déplacez la répétition dans le groupe de capture avec (.*?), vous obtiendrez plus d'un caractère dans le retour.

0

On dirait que c'est la façon de gérer le regroupement. A titre d'exemple plus simple, regardez la différence entre la sortie des lignes de code suivantes:

re.findall("c(a)*t", "hi caaat hi") 
re.findall("c(a*)t", "hi caaat hi") 

Il semble que le code que vous voulez serait plus comme:

re.findall("\|\s*name\s*=([^\|\}]*)", a, re.I) 
0
matched = re.findall("\|?\s*[nN]ame\s*=([a-zA-Z\.\s]+)\|?",a,re.I) 
print matched 

sortie:

['A. Johnson '] 
Questions connexes