最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

Gitlab CI requires you to specify a regex to extract the statements code coverage (so that they can display it). Given the build output below (with jest and istanbul), I've managed to e as far as: /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)

This highlights the part Statements : 53.07% (see here: ). However, I need to match only the 53.07 part, how do I do that?

Gitlab CI requires you to specify a regex to extract the statements code coverage (so that they can display it). Given the build output below (with jest and istanbul), I've managed to e as far as: /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)

This highlights the part Statements : 53.07% (see here: http://regexr./3e9sl). However, I need to match only the 53.07 part, how do I do that?

Share Improve this question edited Sep 23, 2016 at 10:38 vkjb38sjhbv98h4jgvx98hah3fef asked Sep 23, 2016 at 10:23 vkjb38sjhbv98h4jgvx98hah3fefvkjb38sjhbv98h4jgvx98hah3fef 1,6133 gold badges15 silver badges32 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 17

I need to match only the 53.07 part,

Use lazy .*?, add (?:\.\d+)? to also match floats, and access the capture group:

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

Note that Statements.*?(\d+(?:\.\d+)?)% also allows integer values, not only floats.

Pattern description:

  • Statements - a literal string
  • .*? - zero or more chars other than whitespace, but as few as possible
  • (\d+(?:\.\d+)?) - Group 1 (the value you need will be captured into this group) capturing 1+ digits and an optional sequence of . and 1+ digits after it
  • % - a percentage sign (if you need to print it, move it inside parentheses above)

See the regex demo.

发布评论

评论列表(0)

  1. 暂无评论