I need help to complete a regex pattern. I need a pattern to match a range of numbers including unit.
Examples:
- The car drives 50,5 – 80 km/10min on the road.
- The car drives 50,5 – 80 km / 10min on the road.
- The car drives 40,5-80 km/h on the road.
- The car drives 30-50 km/h on the road.
- The car drives 40 – 60.8 km/ h on the road.
- The car drives 40.90-60,8 km/h on the road.
I need to match the entire ranges. Good would also be (?:km/10min|km / 10min|km/h|km/ h) to simplify this part so that this does not have to be listed multiple times. So also here the blanks taken into account.
([,.\d]+)\s*(?:km/10min|km / 10min|km/h|km/ h)
https://regex101.com/r/Ey792V/1
Currently, unfortunately, only the first number is matched. Thanks in advance for the help.
>Solution :
You could make the pattern a bit more specific and optionally match whitespace chars instead of hard coding all the possible spaces variations
\b\d+(?:[.,]\d+)?(?:\s*-\s*\d+(?:[.,]\d+)?)?\s*km\s*/\s*(?:h|10min)\b
Explanation
\bA word boundary\d+(?:[.,]\d+)?Match 1+ digits with an optional decimal part(?:Non capture group\s*-\s*Match-between optional whitespace chars\d+(?:[.,]\d+)?Match 1+ digits with an optional decimal part
)?Close the non capture group and make it optional\s*km\s*/\s*Matchkm/surrounded with optional whitespace chars to match different variations(?:h|10min)Match eitherhor10min(Or use\d+minto match 1+ digits)\bA word boundary
See a regex demo.