2

以下のような python コードがあります: 私の質問は、一致した変数が [' '] である理由は? (regexpal.com で正規表現を使用しました。正しい結果が見つかります |Name=A. Johnson | そこで)

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)
4

3 に答える 3

3

あなたが望む(.*?)のは、ではなく、(.)*?後者(あなたが持っているもの)は、複数の文字を消費する場合でも、単一の文字のみをキャプチャします。グループ自体に繰り返しがある場合でも、キャプチャ グループは 1 回だけ返されます。(.)したがって、後者は繰り返しにもかかわらず単一の文字をキャプチャします。

を使用して繰り返しをキャプチャ グループに移動すると(.*?)、複数の文字が返されます。

于 2012-05-21T02:44:21.790 に答える
0

グループ化の処理方法のようです。より簡単な例として、次のコード行の出力の違いを見てください。

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

必要なコードは次のようになります。

re.findall("\|\s*name\s*=([^\|\}]*)", a, re.I)
于 2012-05-21T02:48:51.433 に答える
0
matched = re.findall("\|?\s*[nN]ame\s*=([a-zA-Z\.\s]+)\|?",a,re.I)
print matched

出力:

['A. Johnson ']
于 2012-05-21T02:53:21.463 に答える