为什么这个正则表达式找不到结果

2024-10-06 00:25:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下python代码:我的问题是为什么匹配的变量是['']?(我用正则表达式)regexpal.com,它可以找到正确的结果| Name=A.Johnson | there)

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)

Tags: revicejohnpoststartendstatewilliam
3条回答

您需要的是(.*?),而不是(.)*?——后者(您拥有的)将只捕获单个字符,即使它消耗的多于单个字符。一个捕获组只返回一次,即使该组本身有一个重复;因此后者捕获一个字符(.),尽管它是重复的。你知道吗

如果用(.*?)将repeat移到capture组中,则返回的字符不止一个。你知道吗

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

输出:

['A. Johnson ']

看起来它是如何处理分组的。作为一个简单的示例,请看以下代码行的输出之间的差异:

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

看起来你想要的代码更像:

re.findall("\|\s*name\s*=([^\|\}]*)", a, re.I)

相关问题 更多 >