Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for series of four digits each up to 100

Tags:

regex

ruby

I'm trying to write a regex to validate a string and accepts only a series of four comma-separated digits, each up to 100. Something like this would be valid:

20,30,40,50

and these invalid:

120,0,20,0
20,30,40,ss
invalid_string

Any thoughts?

They're used for CMYK colours. We just need to store them here, not use them.

like image 441
t56k Avatar asked Feb 03 '26 05:02

t56k


2 Answers

Number Range and Subroutine

In Ruby 2+, for a compact regex, use this:

^([0-9]|[1-9][0-9]|100)(?:,\g<1>){3}$

Explanation

  • The ^ anchor asserts that we are at the beginning of the string
  • The parentheses around ([0-9]|[1-9][0-9]|100) match a number from 0 to 100 and define subroutine #1
  • (?:,\g<1>) matches one comma and the expression defined by subroutine # 1
  • The {3} quantifier repeats that three times
  • The $ anchor asserts that we are at the end of the string
like image 150
zx81 Avatar answered Feb 04 '26 20:02

zx81


I'd save myself the headache of using regex for a number related problem. Also the validation message will look akward so it's better to make your own:

validate :that_string_has_only_4_numbers_upto_100

def that_string_has_only_4_numbers_upto_100
  errors.add(:str, 'is not valid.') unless str.split(/,/).all? { |n| 1..100 === n.to_i }
end

Unless you a re regex jedi guru like @zx81 :p.

like image 34
ichigolas Avatar answered Feb 04 '26 19:02

ichigolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!