Search code examples
regexpython-re

Using Python Re to extract percentages from string


I've been trying to build a python script to download torrent files using transmission cli and I need to print the download progress and abort the script once the download is finished.

So I tried using regex as mentioned in the code block below

out = subprocess.check_output("transmission-remote --auth 'transmission':'transmission' --list", shell=True);
percentage = re.findall(r'^[0-9].+%$', str(out))
print(percentage)

But so far it's returning an empty list and the value of out is as below

ID     Done       Have  ETA           Up    Down  Ratio  Status       Name
   1   100%    5.57 GB  Done        71.0     1.0    0.0  Seeding      Sample
Sum:           5.57 GB              71.0     1.0

Why's the regex not extracting the percentages? Some help is appreciated.


Solution

  • Try this pattern:

    (\d{1,3})%

    The capture group grabs only the digits (that are immediately followed by a percentage % char).