Python: print 4 characters after certain characters in a string

Viewed 178

I need from this line:

 CR: 0.24%    RU   01.07.2021   CR: 0.44%    TJ   01.07.2021   CR: 0.15%    TJ   01.07.2021   CR: 0.18%    TJ   01.07.2021

Get an array like this:

['0.24%', '0.44%', '0.15%', '0.18%']

That is, get 4 characters after CR:

I tried to figure it out with regexes and was able to get one character after CR: My code:

print(re.findall(r'CR: (\w+)', string))

Thanks in advance for your help!

2 Answers

The problem is with \w+ pattern that matches any one or more letter, digits and underscores (with some connector punctuation and diacritics). It does not match . and % chars.

You can use

import re
s = "CR: 0.24%    RU   01.07.2021   CR: 0.44%    TJ   01.07.2021   CR: 0.15%    TJ   01.07.2021   CR: 0.18%    TJ   01.07.2021"
print(re.findall(r'CR:\s*(\d+(?:\.\d+)?%)', s))
# => ['0.24%', '0.44%', '0.15%', '0.18%']

See the regex demo and the Python demo.

You might also just get a word after CR: with spaces:

print(re.findall(r'CR:\s*(\S+)', s))

See the regex demo.

Details:

  • CR: - CR: string (add \b in front if you want to make sure there are no other letters/digits before CR)
  • \s* - zero or more whitespace chars
  • (\d+(?:\.\d+)?%) - Capturing group 1: one or more digits and then an optional occurrence of a dot and one or more digits, and then a % char
  • (\S+) - one or more non-whitespace chars.

Problem

  • '0.24%' is 5 and not 4 characters
  • \w is for [a-zA-Z0-9_] so it doesn't take into account the dot

Solutions

  • .{5} for any 5 chars

    re.findall(r'CR: (.{5})', string) # ['0.24%', '0.44%', '0.15%', '0.18%']
    
  • (\S+) for any amount of non-space chars

    re.findall(r'CR: (\S+)', string) # ['0.24%', '0.44%', '0.15%', '0.18%']
    
  • (\d+\.\d+%) for a precise match of the expected content, float number with % symbol

    re.findall(r'CR: (\d+\.\d+%)', string)
    
Related