12

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 come 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.com/3e9sl). However, I need to match only the 53.07 part, how do I do that?

1 Answers1

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563