如何使用正则表达式从伊斯坦布尔文本摘要报告中提取测试覆盖率?

How do I extract test coverage from the istanbul text-summary reporter with a regex?

本文关键字:提取 测试 测试覆盖 覆盖率 报告 正则表达式 何使用 伊斯坦布尔 文本      更新时间:2023-09-26

Gitlab CI要求您指定一个正则表达式来提取语句的代码覆盖率(以便他们可以显示它)。给出下面的构建输出(jest和istanbul),我已经设法做到了:/Statements.*('d+'%)/

... (other build output)
=============================== Coverage summary ===============================
Statements   : 53.07% ( 95/179 )
Branches     : 66.67% ( 28/42 )
Functions    : 30.99% ( 22/71 )
Lines        : 50.96% ( 80/157 )
================================================================================
... (other build output)

这突出显示了Statements : 53.07%部分(参见这里:http://regexr.com/3e9sl)。但是,我只需要匹配53.07部分,我该怎么做?

我只需要匹配53.07部分,

使用惰性.*?,添加(?:'.'d+)?也匹配浮点数,并访问捕获组:

var re = /Statements.*?('d+(?:'.'d+)?)%/; 
var str = '... (other build output)'n=============================== Coverage summary ==============================='nStatements   : 53.07% ( 95/179 )'nBranches     : 66.67% ( 28/42 )'nFunctions    : 30.99% ( 22/71 )'nLines        : 50.96% ( 80/157 )'n================================================================================'n... (other build output)';
var res = (m = re.exec(str)) ? m[1] : "";
console.log(res);

注意Statements.*?('d+(?:'.'d+)?)%也允许整数值,而不仅仅是浮点数。

<<p> 模式描述/strong>:
  • Statements -一个文字字符串
  • .*? - 0个或多个除空格以外的字符,但尽可能少
  • ('d+(?:'.'d+)?) -组1(您需要的值将被捕获到该组中)捕获1+数字和.的可选序列和后面的1+数字
  • % -一个百分号(如果你需要打印它,把它移到上面的括号里)