Regex:匹配分隔行的字符串



社区,我如何在称为[[runners]]的部分下使用正则表达式匹配nameexecutor

我在玩这样的东西:

(?=.*?(name.*))(?=.*?(executor.*))

(?<=[runners])[sS](s*name.*)

/(?<=[[runners]])[sS](?=.*?(name.*))(?<=[sS])(?=.*?(executor.*))/g

文件的例子:

[[runners]]
name = "admin"
url = "url"
token = "token"
executor = "shell"
[runners.custom_build_dir]
[runners.cache]
[runners.cache.s3]
[runners.cache.gcs]
[runners.cache.azure]
[[runners]]
name = "admin2"
url = "url"
token = "token"
executor = "docker"
[runners.custom_build_dir]
[runners.cache]
[runners.cache.s3]
[runners.cache.gcs]
[runners.cache.azure]

预期结果:

[[runners]]  
name = "admin"
executor = "shell"
[[runners]]
name = "admin2"
executor = "docker"

更新:根据@PoulBak的评论,我的最终解决方案是

grep -E '[[runners]]|name = "[^"]+"|executor = "[^"]+"' /etc/gitlab-runner/config.toml

我做了一个演示,使用javascript作为正则表达式的执行者。

我的策略是使用双换行符作为分隔符分割输入字符串,使用以下语句:

data.split(/nn/img);

然后对于上面返回的每个runner元素,使用两个不同的正则表达式来获取属性名称和执行器。

输出将包含在输入中找到的任何运行器的字符串[[runners]],但只有在相应运行器的输入中存在属性名称或执行器时才会列出。

对于这个任务,一个合适的解析器会更合适,因为您可以让光标移动到下一行,并保持正在进行的状态。无论如何,我尽了最大的努力来包含这个任务的性能绘图,同时在任何可能的地方使用正则表达式。

const data = `
[[runners]]
name = "admin"
url = "url"
token = "token"
executor = "shell"
[runners.custom_build_dir]
[runners.cache]
[runners.cache.s3]
[runners.cache.gcs]
[runners.cache.azure]
[[runners]]
name = "admin2"
url = "url"
token = "token"
executor = "docker"
[runners.custom_build_dir]
[runners.cache]
[runners.cache.s3]
[runners.cache.gcs]
[runners.cache.azure]
[[runners]]  
url = "runnerWithNoName"
token = "token"
executor = "docker"
[runners.custom_build_dir]
[runners.cache]
[runners.cache.s3]
[runners.cache.gcs]
[runners.cache.azure]  
`;
let output = '';
const runners = data.split(/nn/img);
for(let runner of runners){  
const name = /s*name = "([^"]*)"/.exec(runner);
const executor = /s*executor = "([^"]*)"/.exec(runner);  
output += "[[runners]]n";
if(name !== null) output += name[0].trim() + "n";
if(executor !== null) output += executor[0].trim() + "n";  
}
console.log(output);

相关内容

  • 没有找到相关文章

最新更新