Skip to content

Instantly share code, notes, and snippets.

@ValterAndrei
Last active July 27, 2022 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ValterAndrei/d1a3a0825c7326afa68a0a147e236d32 to your computer and use it in GitHub Desktop.
Save ValterAndrei/d1a3a0825c7326afa68a0a147e236d32 to your computer and use it in GitHub Desktop.
Regex for CPF and CNPJ
  • CPF
/^\d{3}\.\d{3}\.\d{3}\-\d{2}$/
  • CNPJ
/^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$/
  • Both
/(^\d{3}\.\d{3}\.\d{3}\-\d{2}$)|(^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$)/
  • Ruby
'256.515.510-77'.match? /\d{3}\.\d{3}\.\d{3}\-\d{2}$/

# ou
is_license_plate_like = ->(value) { value =~ /\A[A-Z]{3}-?\d[0-9A-Z]\d{2}\z/i }
is_cpf_like = ->(value) { value =~ /\A\d{3}.?\d{3}.?\d{3}-?\d{2}\z/i }
is_cnpj_like = ->(value) { value =~ %r{\A\d{2}\.?\d{3}\.?\d{3}/?\d{4}-?\d{2}\z}i }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment