Marco Herrarte
Marco Herrarte

Reputation: 1620

Ruby Regular expression to get percentage from specific line

I have the following output:

Name                              Stmts   Miss  Cover   Missing
---------------------------------------------------------------
src/global_information.py             8      1    88%   6
src/settings.py                      38      0   100%
src/storage_backends.py               4      4     0%   1-5
src/urls.py                           8      0   100%
users/admin.py                        1      0   100%
users/apps.py                         3      3     0%   1-5
users/forms.py                        5      0   100%
users/models.py                       1      0   100%
users/tests/tests_views_urls.py       5      0   100%
users/urls.py                         5      0   100%
users/views.py                        1      1     0%   1
---------------------------------------------------------------
TOTAL                                79      9    89%

I need to get the TOTAL percentage, which is 89%. I try the following two regex:

TOTAL\s+\d+\s+\d+\s+\d+\%

and

(?<=TOTAL\s).*

I can get the correct line but not sure how to extract the percentage part of it. This needs to be achieved in a regular expression due that I don’t have access to any tool

Thanks

Upvotes: 0

Views: 112

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

str=<<_
Name                              Stmts   Miss  Cover   Missing
---------------------------------------------------------------
src/global_information.py             8      1    88%   6
src/settings.py                      38      0   100%
src/storage_backends.py               4      4     0%   1-5
src/urls.py                           8      0   100%
users/admin.py                        1      0   100%
users/apps.py                         3      3     0%   1-5
users/forms.py                        5      0   100%
users/models.py                       1      0   100%
users/tests/tests_views_urls.py       5      0   100%
users/urls.py                         5      0   100%
users/views.py                        1      1     0%   1
---------------------------------------------------------------
TOTAL                                79      9    89%
_

str[/^TOTAL.*?\K\d+%/] #=> "89%

\K means discard everything matched so far. The non-greedy modifier ? in .*? is needed. Without it the match before \K would end with the next-to-last digit in the total percentage (here the "8" in "89%", the "3" in "1234%").

Upvotes: 1

Federico Piazza
Federico Piazza

Reputation: 30995

You can use a regex like this:

TOTAL.*?(\d+)%

Working demo

Or if you want to capture the % then

TOTAL.*?(\d+%)

Then grab the content from the capturing group $1

Upvotes: 2

delta
delta

Reputation: 3818

awk '/TOTAL/{ print $4}' <INPUT_FILE>

Upvotes: 0

Related Questions