Regex pattern to see if a string contains a number in a range

  • A+
Category:Languages

I'm trying to match a number between 400 and 499 anywhere in a string. For example, both:

string = "[401] One too three" string2 = "Yes 450 sir okay" 

should match. Both:

string3 = "[123] Test" string4 = "This is another string" 

should fail.

What's the best way to write the regex? I wrote:

string =~ //d{3}/ 

to see if the string contains a three digit integer. How can I see if that's within the range?

 


If you don't actually need the number afterwords, and just need to determine yes or no the string contains a number in the range of 400-499, you can:

  1. Check that you are at the beginning of a line, or have a non-digit character followed by
  2. the digit '4' followed by
  3. Any 2 digits followed by
  4. the end of a line or a non-digit character

so you end up with a regex looking something like

regex = /(?:^|/D)4/d{2}(?:/D|$)/ 

or, by using negative look ahead/look behinds:

regex = /(?<!/d)4/d{2}(?!/d)/ 

and you need step 1 and 4 above to make rule out numbers such as 1400-1499 and 4000-4999 (and other such numbers with more than 3 digits that have 400-499 somewhere buried in them). You can then make use of String#match? in newer ruby versions to get just a simple boolean:

string.match?(regex)   # => true string2.match?(regex)  # => true string3.match?(regex)  # => false string4.match?(regex)  # => false "1400".match?(regex)   # => false "400".match?(regex)    # => true "4000".match?(regex)   # => false "[1400]".match?(regex) # => false "[400]".match?(regex)  # => true "[4000]".match?(regex) # => false 

Fairly simple regex, no need to pull out the match and convert it to an integer if you just need a simple yes or no

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: