2017-05-19 25 views
0

我有以下代碼:file.match(正則表達式)不匹配文件名提供

fs.readdir('.', (err, files) => { 
    files.forEach(file => { 
     if (file.match(/^\Qcustom_\E.+\d\Q.pid\E/)) { 
      var pid = fs.readfile(file, function (err, data) { 
       if (err) throw err; 
       return data.toString(); 
      }); 
      console.log(pid); 
     } 
    }); 
}); 

而在我的目錄,我有幾個文件,如custom_Component1.pidcustom_Component2.pidcustom_NewComponent3.pid等,與這些含只有一行(pid)。

但是,上面的代碼與文件不匹配,即使根據我的Regex101,正則表達式是正確的。

如果我console.log(file),文件名顯示出來我究竟是如何指望它,就像custom_Component1.pid

+1

你忘了切換到JavaScript模式嗎?它在JavaScript模式下不適用於我,但在PHP模式下工作。你不需要混淆\ Q \ E,只需使用'custom _。+?\ d \ .pid' – markbernard

+1

使用'/^custom _。+ \ d \ .pid /'Dot必須轉義以匹配文字點。 –

回答

1

它看起來並不像Javacript支持\Q\E,請查看以下內容:Javascript equivalent of Perl's \Q ... \E or quotemeta()

爲什麼贏」 t以下正則表達式工作?如果您需要更嚴格的匹配,請描述您的具體要求,我相信您會得到一個可以正常使用的正則表達式的快速響應。

/^custom_.+\d\.pid/g