Search code examples
regexnumbersrange

Detect sentences that contain a valid number range


I am trying to write a regex expression that detects sentences that have a number range, for example: "I eat 2-6 pizzas per day" "My weight is between 50.22-220.5 kg."

But not numbers with more hyphens: "My phone number is 1-23-4567" Or with : "I use WD-40 to put my pants on."

So far I have come up with:

\b\d+-\d+\b

But it still detects things like 123-2312-12.


Solution

  • If lookarounds are supported, you could write the pattern as:

    (?<!\S)\d+(?:\.\d+)?-\d+(?:\.\d+)?(?!\S)
    

    Explanation

    • (?<!\S) A whitespace boundary to the left
    • \d+(?:\.\d+)? Match 1+ digits with an optional decimal part
    • - Match literally
    • \d+(?:\.\d+)? Match 1+ digits with an optional decimal part
    • (?!\S) A whitespace boundary to the right

    See a regex demo.