javascript - 如何从正则表达式匹配函数中获取匹配的组?

标签 javascript node.js regex pattern-matching regex-group

基本上我正在尝试使用正则表达式获取导入的模块名称,并且我的正则表达式是正确的。所以我在代码中使用了它,但我得到了奇怪的东西而不是模块名称。我想要得到的是 group #1 中的 adsf 字符串。

enter image description here

这是代码。

for(let js of jsFiles) {
    const codes = await fs.readFile(js, 'utf8')
    const regex = /(?:from |require\()'([^/.][^/]*?)'/g
    let arr = codes.match(regex)
    console.log("arr", arr)
  }

这是输出。

arr [ 'require(\'fs-extra\'' ]
arr [ 'require(\'fs-extra\'', 'require(\'path\'' ]
arr [ 'require(\'babel-polyfill\'',
  'require(\'child-process-promise\'',
  'require(\'fs-extra\'',
  'require(\'chalk\'',
  'require(\'ora\'',
  'require(\'querystring\'' ]
arr [ 'from \'ora\'', 'from \'fs-extra\'', 'from \'glob-promise\'' ]
arr [ 'from \'fs-extra\'' ]
arr [ 'from \'fs-extra\'' ]
arr [ 'from \'chalk\'', 'from \'ora\'' ]
arr null
arr null
arr [ 'require(\'bluebird\'', 'require(\'child_process\'' ]
arr null
arr [ 'from \'child-process-promise\'',
  'from \'chalk\'',
  'from \'ora\'' ]

如何修复它?

最佳答案

在循环中使用 regex.exec(codes) 而不是 codes.match(regex):这样您将获得每个组的捕获文本。

一个输入的示例:

const codes = `
    require('babel-polyfill');
    require('child-process-promise');
    require('fs-extra');
    require('chalk');
    require('ora');
    require('querystring');
`;
const regex = /(?:from |require\()'([^/.][^/]*?)'/g,
    arr = [];
let match;
while (match = regex.exec(codes)) arr.push(match[1]);
console.log("arr", arr)

请注意,match[1] 表示与第一个捕获组匹配的内容。 match[0] 将为您提供完整的匹配,就像使用 match 方法(当与 g 修饰符一起使用时)。

关于javascript - 如何从正则表达式匹配函数中获取匹配的组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48129951/

相关文章:

javascript - 使用 javascript(或 jQuery)选择和操作 CSS 伪元素,例如::before 和::after

javascript - 在 ng-repeat 中绑定(bind) ngmodel 的正确方法

javascript - Redux:连接函数中的对象解构?

Python 正则表达式 : exclude\r\n

regex - 在Unix中格式化日期以包括日期(st,nd,rd和th)的后缀

javascript - 从数组中的所有对象中提取某些属性

javascript - 设置@grant值后如何访问 `window`(目标页面)对象?

node.js - 在不重新启动应用程序的情况下设置 Heroku 环境变量

javascript - 将元素插入数组仅在循环内有效

c# - 正则表达式匹配 C# 中的路径