1

I have a long string, that contains

Current: 98%

exactly one time. The percentage can be everything between 0 and 100.

E.g.:

This is a multi-line
output and the battery level is
Current: 100%
Thank you.

How can I just get the value between Current: and %?

DirkReuter
  • 23
  • 3
  • Hi. This is a duplicate of [this post](https://stackoverflow.com/questions/12736074/regex-matching-between-two-strings) – MYousefi Feb 02 '22 at 17:31
  • Does this answer your question? [Regex matching between two strings?](https://stackoverflow.com/questions/12736074/regex-matching-between-two-strings) – MYousefi Feb 02 '22 at 17:32
  • 1
    For sure the regex is a better solution, but if the pattern is that much simple, you can simply use `"""This is a multi-line output and the battery level is Current: 100% """.split(": ")[1].split("%")[0]`, and there is no need to import a library. – A D Feb 02 '22 at 17:39

4 Answers4

1

You could use an approach such as the one below, using regular expressions.

import re
test = """
This is a multi-line
output and the battery level is
Current: 100%
Thank you.
"""
print(re.search(r'Current: (.*?)%', test).group(1))

EDIT: If you need an integer out, you can just wrap the final value with int():

result = int(re.search(r'Current: (.*?)%', test).group(1))
oflint_
  • 297
  • 1
  • 8
0

You can use regex groups to pull out the percentage. This will match a numerical value between Current: (with a space) and the % symbol.

import re

text = """This is a multi-line
output and the battery level is
Current: 100%
Thank you."""

pattern = re.compile(r"Current: ([0-9]+)%")

result = re.search(pattern, text)
print(result.group(1))
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
0

you can use the filter function on a string if you dont like re

int("".join(filter(str.isdigit, long_string)))
edel-david
  • 66
  • 1
  • 4
0

Using a regular expression for this exercise is overkill. Instead, find the position of the percent sign, trim the string at that position, split it, and take the last element:

text[:text.index('%')].split()[-1]
# '100'

I assume that there is only one % in the string.

DYZ
  • 55,249
  • 10
  • 64
  • 93