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

RegEx for matching a word after specific word in multiple lines

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

例如,如何使用正则表达式过滤具有特定 "message" 属性 的那些 "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 中可视化其他表达式:

性能测试

此脚本returns 字符串针对表达式的运行时。

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, "");
}

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}`);
    });
}

VSCode uses RipGrep which uses Rust regex.

以下模式将匹配 'message'

到select直到行尾,

(?<=someFunction.*(\n.+)+)message.*$

到select只有key,省略.*$

(?<=someFunction.*(\n.+)+)message

在您的模式 someFunction[.*\s*]*message 中,您可以使用 character class,它将仅匹配几个字符中的一个,可以写成 [.*\s]

使用像 [\S\s]* 这样的模式不会考虑任何其他具有相同名称的函数或像 }) 这样的闭合边界,并且会过度匹配它。

如果 pcre2 未启用,this page 说明了如何使用前瞻功能启用它。

如果你想要更精确的匹配,你可以使用:

^someFunction\(\{(?:\n(?!(?: +message:|}\))).*)*\n +message:(.*)\n}\)$

说明

  • ^ 字符串开头
  • someFunction\(\{ 匹配 someFunction({
  • (?:非捕获组
    • \n 匹配换行符
    • (?! 否定前瞻
      • (?:非捕获组
        • +message: 匹配 1+ 个空格后跟消息:
        • |
        • }\) 匹配 })
      • )关闭非捕获组
    • ) 关闭否定前瞻
    • .* 匹配除换行符外的任何字符
  • )*关闭无捕获组重复0+次
  • \n +message: 匹配换行符和消息:
  • (.*)\n 在组 1 中捕获匹配除换行符后跟换行符之外的任何字符
  • }\) 匹配 })
  • $ 字符串结束

Regex demo

您可以在 VScode 中使用正则表达式进行多行搜索。

如果您在文件中有多个 someFunction,而您只想查找具有消息字段的函数,而跳过其他没有消息字段的函数。

使用以下内容

  • 使用惰性限定符+?,它匹配从第一次出现someFunction到第一次出现message
  • 的文本块
  • 使用[^)]确保someFunctionmessage
  • 之间没有右括号
  • 使用\n匹配多行
someFunction([^)]|\n)+?message: