正则表达式无法在Array.prototype.filter方法中正常工作

时间:2017-05-22 13:08:08

标签: javascript node.js regex

我在今天使用简单的正则表达式测试过滤掉结果时遇到的奇怪行为。

我有一个简单的正则表达式定义:

const pkgSourcePathRe = new RegExp('packages\/[a-zA-Z0-9-]+\/source\/', 'g');

这个正则表达式逐行测试多行字符串:

const stdout = `.babelrc
package.json
packages/pilot/build/index.js
packages/pilot/source/index.js
packages/rexponse-resolver-react-redux/source/index.js
packages/rexponse/build/authenticators/accountkit.js
packages/rexponse/build/index.js
packages/server-skeleton/build/getSettings.js
packages/viewer/source/index.js`

正如您可能猜到的结果应该是:

packages/pilot/source/index.js
packages/rexponse-resolver-react-redux/source/index.js
packages/viewer/source/index.js

但是“packages / rexponse-resolver-react-redux / source / index.js”没有通过测试。我明白了:

packages/pilot/source/index.js
packages/viewer/source/index.js

如果我独立运行测试:

pkgSourcePathRe.test('packages/rexponse-resolver-react-redux/source/index.js')

我得到true

以下是我在我的应用中运行的代码段:

const stdout = `.babelrc
package.json
packages/pilot/build/index.js
packages/pilot/source/index.js
packages/rexponse-resolver-react-redux/source/index.js
packages/rexponse/build/authenticators/accountkit.js
packages/rexponse/build/index.js
packages/server-skeleton/build/getSettings.js
packages/viewer/source/index.js
`

const lineBreakRe = new RegExp('\n', 'gm');
const pkgSourcePathRe = new RegExp('packages\/[a-zA-Z0-9-]+\/source\/', 'g');
let changedFiles = stdout.split(lineBreakRe);
let changedPkgSources = [];
if (changedFiles && changedFiles.length > 0) {
  changedFiles = changedFiles.filter(file => file);
  if (changedFiles.length > 0) {
    changedPkgSources = changedFiles
      .filter(file => {
        const result = pkgSourcePathRe.test(file)
        console.log('Test result of "'+file+'" is '+ String(result))
        return result
      })
      .map(file => {
        const arr = file.split('/');
        return arr[1];
      });
  }
}

您会看到packages/rexponse-resolver-react-redux/source/index.js的正则表达式测试结果为false

有没有人知道这种奇怪行为的原因是什么?

0 个答案:

没有答案