RegEx用于在多行中的特定单词之后匹配单词

时间:2019-05-08 03:39:45

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

在诸如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/

但这没用

我如何实现这个目标?

4 个答案:

答案 0 :(得分:3)

您的表达式很好,您可能需要对其稍作修改:

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

答案 1 :(得分:1)

在模式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

答案 2 :(得分:1)

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

如果文件中有几个 someFunction 并且只想找到有 message 字段的那些而跳过其他没有 message 字段的那些。

使用以下内容

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

enter image description here

enter image description here

答案 3 :(得分:0)

VSCode uses RipGrep,它使用Rust regex

以下模式将匹配“消息”

要选择到行尾,

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

仅选择键,请省略。* $

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