正则表达式查找函数调用的字符串参数(多次命中后查找)

问题描述 投票:0回答:1

我想使用 grep (PCRE) 查找传递给我的函数的所有单引号字符串

foo()

我的源代码中的示例函数调用和预期的命中:

foo('Alice')                    -> Expected Hits: Alice
foo('Alice', 'Bob', 'Charlie')  -> Expected Hits: Alice, Bob, Charlie
foo(flag ? 'Alice' : 'Bob')     -> Expected Hits: Alice, Bob

我的正则表达式:

foo\([^\)]*\K(?:')([^'\)]*)(?:'\))

但是,我只获得每个函数调用的最后一个单引号字符串,而不是您在我的 regex101 游乐场中看到的所有字符串:https://regex101.com/r/FlzDYp/1

如何为 grep 定义符合 PCRE 的正则表达式以获得所有预期的命中?

regex grep regex-group pcre regex-greedy
1个回答
0
投票

在 JavaScript 中,我们可以匹配所有函数调用,然后再次使用

match
查找所有字符串参数:

var input = `foo('Alice')
foo('Alice', 'Bob', 'Charlie')
foo(flag ? 'Alice' : 'Bob')`;

var matches = input.match(/\w+\(.*?\)/g);
var strings = matches.map(x => x.match(/'.*?'/g));
for (var i=0; i < matches.length; ++i) {
    console.log(matches[i] + " => " + strings[i]);
}

© www.soinside.com 2019 - 2024. All rights reserved.