2017-04-17 2 views
0

私はリスト(配列)とのマッチングにPythonを使用していますが、問題は正規表現そのものにあると確信しています。正規表現が1番目の結果を超えて一致する

私は、次のしていると仮定:

foo.html 
bar.html 
teep.html 

そして、私は、次の正規表現を使用します。.*(?=.html)

.*は何もマッチします

(?=.html)は、文字列が存在する必要がありますが、結果に含めていません

したがって、私はちょうど前のものと一緒に残すべきです.html

私がチェックすると、それだけで(この場合fooで)配列内の最初の項目に一致するが、なぜ他の人

my_regex = re.compile('.html$') 
r2 = re.compile('.*(?=.html)') 
start = '/path/to/folder' 
os.chdir(start) 
a = os.listdir(start) 
for item in a: 
    if my_regex.search(item) != None and os.path.isdir(item): 
     print 'FOLDER MATCH: '+ item # this is a folder and not a file 
     starterPath = os.path.abspath(item) 
     outer_file = starterPath + '/index.html' 
     outer_js = starterPath + '/outliner.js' 
     if r2.match(item) != None: 
      filename = r2.match(item).group() # should give me evertying before .html 
     makePage(outer_file, outer_js, filename) # self defined function 
    else: 
     print item + ': no' 
+0

コードを表示してください。 WiktorStribiż[email protected] –

+0

はまあ、 'R – Kervvv

+0

追加 '*(?= \。htmlの)''あなたのためのより良い正規表現であるが、主な問題は、正規表現ではありません。 –

答えて

1
filename = r2.match(item).group() 

は、ドキュメントによると

filename = r2.match(item).groups() # plural ! 

する必要がありませんgroupsはそれらをすべて返します。一方、groupは、一つ以上のサブグループを返します。

+0

更新のための私の答えを参照してください。 '.groups()'は残念なことに動作しましたが、問題を引き起こしていないことが判明しました。単純な新人デベロッパーの間違い。 – Kervvv

1

問題を解明しました。私の機能では、ディレクトリを変更しましたが、元に戻ったことはありません。関数が終了してforループに戻ると、間違った場所にあるフォルダ名を探していました。それは同じくらい簡単.group()また

def makePage(arg1, arg2, arg3): 
    os.chdir('path/to/desktop') 
    # write file to new location 
    os.chdir(start) # go back to start and continue original search 
    return 

としては、私のために働いたと .groups()がちょうどオリジナルのポスト内のコードが同じ滞在

()を返されたのに対し、文字列.html前に、フォルダ名のすべてを返されます。とても簡単なことで、この頭痛を引き起こします。

関連する問題