How to get "m" meters and "km" from string using regex?

by elisha_langworth , in category: Third Party Scripts , a month ago

How to get "m" meters and "km" from string using regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , a month ago

@elisha_langworth 

You can use the following regular expression to extract the meters (m) and kilometers (km) values from a string:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import re

# Sample string
string = "I ran 5km and then walked 300m."

# Pattern to extract meters and kilometers
pattern = r'(d+)s*(m|km)'

# Find all matches in the string
matches = re.findall(pattern, string)

# Print the matches
for match in matches:
    print(f"Value: {match[0]}, Unit: {match[1]}")


This code snippet will output:

1
2
Value: 5, Unit: km
Value: 300, Unit: m


You can adjust the pattern and code as needed based on the specific format of the string you are working with.