ROR Regex. I am trying to validate that the first and fourth characters in the string are any numbers other than 0 or 1

Viewed 90

I cannot find a solution on google or SO

This works for the first character

validates :number, format: { with: /\A[2-9]/ }

and this works for the fourth character

validates :number, format: { with: /\A...[2-9]/ }

But for the life of me i cannot figure out how to sort of merge these to validate both. Please help

2 Answers

Use

validates :number, format: { with: /\A[2-9].{2}[2-9]/m }

Explanation

--------------------------------------------------------------------------------
  \A                       the beginning of the string
--------------------------------------------------------------------------------
  [2-9]                    any character of: '2' to '9'
--------------------------------------------------------------------------------
  .{2}                     any character (2 times)
--------------------------------------------------------------------------------
  [2-9]                    any character of: '2' to '9'

You can use [\w\W]{2} to indicate any 2 characters:

/A[2-9][\w\W]{2}[2-9]/
Related