在某些编辑器(如 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 .
图
此图显示了您的表达式如何工作,您可以在 jex.im 中可视化其他表达式:
性能测试
此脚本根据表达式返回字符串的运行时间。
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/