laosnd
laosnd

Reputation: 127

Search in a string using regex [python]

I'm searching this text:

22min 7s 11.2km

The pattern is always: {1,2} numbers + 'min' + space + {1,2} numbers + 's' + space + {1,2,3} numbers + . + {1,2} numbers + 'km'

*spaces can ou cannot exist - and sometimes . is coming as ,

I'm using re.search to find but I'm having problems.

item = re.search('\s(\d{1,2}\w{min}\d{1,2}\w{s}\s{1,2,3}\w{km})', img1).group(1)

Upvotes: 0

Views: 476

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627468

You can use

m = re.search(r'\d{1,2}min\s+\d{1,2}s\s+\d+(?:[.,]\d+)?km', img1)
if m:
    item = m.group()

See the regex demo. Details:

  • \d{1,2} - one or two digits
  • min - a word min
  • \s+ - one or more whitespaces
  • \d{1,2}s - one or two digits and s
  • \s+ - one or more whitespaces
  • \d+(?:[.,]\d+)? - one or more digits, and then . or , and one or more digits (optionally)
  • km - a km string.

Upvotes: 1

Related Questions