-1

I want to extract all numbers that look like they may indicate a range in distances using regex in python.

s = "3 to 6 km. 3 - 6 km"
re.findall(r'(\d [(to)|\-] \d km)', s)

# desired result ['3 to 6 km', '3 - 6 km']
# result: ['3 - 6 km']

How can I modify this to get the desired result?

Edward
  • 113
  • 1
  • 8

1 Answers1

3

You can omit the outer capture group and use a single alternation using a non capture group for either to or -:

\d+ (?:to|-) \d+ km

Regex demo

import re

s = "3 to 6 km. 3 - 6 km"
print(re.findall(r'\d+ (?:to|-) \d+ km', s))

Output

['3 to 6 km', '3 - 6 km']
The fourth bird
  • 154,723
  • 16
  • 55
  • 70