Home > Back-end >  Regex for matching number ranges with specific units
Regex for matching number ranges with specific units

Time:05-02

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.

CodePudding user response:

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

  • \b A 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* Match km/ surrounded with optional whitespace chars to match different variations
  • (?:h|10min) Match either h or 10min (Or use \d min to match 1 digits)
  • \b A word boundary

See a regex demo.

CodePudding user response:

\d. (?:h\b|min\b|s\b)

Would also work. Demo

  • Related