Home > Enterprise >  Detect sentences that contain a valid number range
Detect sentences that contain a valid number range

Time:12-27

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.

CodePudding user response:

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.

CodePudding user response:

I'm afraid your question is way too broad and cannot necessarily be handled by a static regex, but I'll try to give you an essence of how to go about implementing ranges using regex. So, the following pattern for example:

[2-6][1-8]

matches any number between 21 and 68.

You could use something like this, and try to implement what you want, but as I said, it would be difficult all kinds of ranges with a static regex. You can try and play with it here.

CodePudding user response:

This solution excludes all not allowed sequences:

(?!(()|())) excludes patterns with an OR | condition

(\d -\d -) excludes sentences which contain digits in the form of 1-23-

([A-Z]-\d ) ecludes all big letters followed by a hyphen and a digit. like D-4.

^((?!(\d - \d -)|[A-Z]-\d ).) $
  • Related