Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

python - why this regex cannot find the result

I have a python code like below: My question is why the matched variable is [' ']? (I used the regex in regexpal.com, it can find the right result |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*names*=(.)*?|",a,re.I)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll want (.*?), not (.)*?—the latter (what you have) will only capture a single character, even if it consumes more than a single one. A capture group will only be returned once even if the group itself has a repeat; so the latter captures a single character (.) despite its repeat.

If you move the repeat into the capture group with (.*?), you'll get more than a single character in the return.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...