1
ALTER TABLE users ADD CONSTRAINT users_email_check 
    CHECK ( email ~ '\\A(?i-mx:[\w\.%\+\-]+)@(?i-mx:(?:[a-z0-9\-]+\.)+)(?i-mx:[a-z]{2,})\\Z' );

The above PostgreSQL column constraint gives:

ERROR: invalid regular expression: quantifier operand invalid

Note, the double backslash at Start and End of String anchors were necessary for escape because the statement is placed inside a heredoc.

1
  • Try email ~* '^(?:[\w.%+-]+)@(?:(?:[a-z0-9-]+\.)+)(?:[a-z]{2,})$' Commented Sep 12, 2020 at 4:27

1 Answer 1

1

I figured it out. The regex had two (2) issues:

  1. The ?i-mx: were the by-product of interpolating regex inside regex in Ruby. I simply copied and pasted the resulting interpolation from Ruby. PostgreSQL didn't know how to handle them, and they're unnecessary.

  2. I needed to double-up on all backslashes, like I did for Start and End of String, since the entire statement is placed inside a heredoc.

This is the correct version:

email ~ '\\A[\\w\\.%\\+\\-]+@(?:[a-z0-9\\-]+\\.)+(?:[a-z]{2,})\\Z'
Sign up to request clarification or add additional context in comments.

1 Comment

You are overescaping, use '^[\\w.%+-]+@(?:[a-z0-9-]+\\.)+[a-z]{2,}$'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.