Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex for matching number ranges with specific units

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

([,.\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

  • \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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading