user3084559
user3084559

Reputation: 1

How would i write regex for 250 or more?

Been stuck on this for a while now. How would I write regular expression to match 250 and all numbers greater than 250? By that I mean lets say I want to match all tickets that cost £250 or more.

Upvotes: 0

Views: 2593

Answers (5)

Babak Naffas
Babak Naffas

Reputation: 12571

You could use regex to identify the numeric value in the text and then parse and compare to perform any value-based logic.

Upvotes: 1

pho
pho

Reputation: 25489

Although it doesn't make sense to use Regexp for numeric comparisons, here's a way to do it:

First, lets see what all numbers greater than 250 have in common:

Case 1: 250 <= x <= 299

  • 3 digits
  • 2 is the first digit
  • Second digit is between 5 and 9
  • Third digit is between 0 and 9

The regular expression to match this would be: /2[5-9][0-9]/

Case 2: 300 <= x <= 999

  • Number of digits is 3
  • First digit between 3 and 9
  • All other digits between 0 and 9

The regular expression for this would be: /[3-9][0-9]{2}/

Case 3: x >= 1000

  • 4 or more digits
  • First digit is non-zero

The regexp here is: /[1-9][0-9]{3,}/

Joining these with an OR condition, you get the full regexp as:

/£(2[5-9][0-9]|[3-9][0-9]{2}|[1-9][0-9]{3,})/

Of course, a much simpler way would be to just pull out the number, and then compare the $1 capturing group in a programming language like so:

/£(\d{1,})/

EDIT: To include decimals, append \.[0-9]{0,2} to allow matches to £999, £999.5 and £999.99.

However, keep in mind that this isn't really needed if you just want to check if the number is greater, because the original RegExp will return true for cases like £999.99 too, even though it will just match the integer part.

Upvotes: 3

ThisGuy
ThisGuy

Reputation: 2395

While it is possible, Regex is not really designed to easily compare numbers as discussed here: Is there a simple regex to compare numbers to x?

Regex can be used to parse out the number like this:

£(\d+)

Then you can compare the number found ($1) against the limits.

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96276

Tailor it to your regex engine:

([1-9][0-9]{3,}|[3-9][0-9]{2}|2[5-9][0-9])

Upvotes: 0

senshin
senshin

Reputation: 10360

Here is a Python-style regex that will probably do what you want it to do:

\d{4,}|[3456789]\d{2}|2[56789]\d

It matches all digit strings 4 characters in length or more, as well as those 3 characters in length that begin with a number greater than 2, as well as those 3 characters in length that begin with a 2 and have a second character greater than 4.

This will only match positive integers correctly.

Upvotes: 0

Related Questions