javascript - 用于匹配多行中特定单词后的单词的正则表达式

标签 javascript regex visual-studio-code regex-group regex-greedy

在某些编辑器(如 VS Code)中,有正则表达式功能可以查找单词而不是“Ctrl + F”,我试图在特定单词后用其他几行查找单词。

例如,如何使用正则表达式过滤那些具有特定“消息”属性的“someFunction”,如下所示:

...
someFunction({
  a: true,
  b: false
})
someFunction({
  a: true,
  b: false,
  c: false,
  d: true,
  message: 'I wnat to find the funciton with this property'
})
someFunction({
  a: true
})
...

我试过的正则表达式是这样的:

/someFunction[.*\s*]*message/

但是没有成功

我怎样才能实现这个目标?

最佳答案

你的表达很好,你可能想稍微修改一下:

 someFunction[\S\s*]*message

如果您还希望获得该属性,此表达式可能有效:

(someFunction[\S\s*]*message)(.*)

您可以添加额外的边界,如果您愿意,可以使用 regex101.com .

enter image description here

此图显示了您的表达式如何工作,您可以在 jex.im 中可视化其他表达式:

enter image description here

性能测试

此脚本根据表达式返回字符串的运行时间。

repeat = 1000000;
start = Date.now();

for (var i = repeat; i >= 0; i--) {
	var string = "some other text someFunction \n            \n message: 'I wnat to find the funciton with this property'";
	var regex = /(.*)(someFunction[\S\s*]*message)(.*)/g;
	var match = string.replace(regex, "$3");
}

end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match 💚💚💚 ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. 😳 ");

const regex = /(someFunction[\S\s*]*message)(.*)/;
const str = `...
someFunction({
  a: true,
  b: false
})
someFunction({
  a: true,
  b: false,
  c: false,
  d: true,
  message: 'I wnat to find the funciton with this property'
})
someFunction({
  a: true
})
...`;
let m;

if ((m = regex.exec(str)) !== null) {
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

关于javascript - 用于匹配多行中特定单词后的单词的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56033205/

相关文章:

javascript - 仅查看图像的某些部分

javascript:window.print() 打印 2 页,而我有 1 页

JavaScript 正则表达式 : why is alternation not ordered?

c# - 正则表达式获取以@开头的所有内容并删除所有未包含字符之后的所有内容

javascript - vscode : Const value underlined red

linux - 在 Visual Studio Code 中调试时出现未绑定(bind)方法异常

javascript - 如何将 jquery 变量作为属性传递到输入中

javascript - 使用 HTML + JavaScript 实现多列组合框

javascript - javascript中的正则表达式复杂吗?

visual-studio-code - 自定义按钮未显示在 VS 代码编辑器标题菜单栏中