Home > Back-end >  Ruby regex. Limit min and max string length
Ruby regex. Limit min and max string length

Time:10-01

requirments:

  • min 5, max 50 symbols
  • only uppercase letters and 0-9
  • . / - space no more that 1 in a row
  • can not start and end with this special symbols

Already got \A[A-Z0-9] (?:[.\/ -][A-Z0-9] )*\z. It works fine but does not validate string length. How to add min-max length validation?

CodePudding user response:

You can add a look-ahead at the start of the pattern to "scan" the total string length, before performing the other pattern checks. To match strings of a min-length 5 and max-length 50, add this to the start of the pattern:

(?=.{5,50}\z)
  • Related