Skip to content

Instantly share code, notes, and snippets.

@rdornas
Created June 8, 2022 12:55
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 rdornas/0f16e2e3f9ab405a5f3ffd28b734a959 to your computer and use it in GitHub Desktop.
Save rdornas/0f16e2e3f9ab405a5f3ffd28b734a959 to your computer and use it in GitHub Desktop.
R - Transforma um texto (string) em CNPJ
# Função para transformar uma string em CNPJ.
str_cnpj <- Vectorize(function(x) {
# Remove todas as pontuações do string
y <- stringr::str_remove_all(stringr::str_squish(x), "[[:punct:]]")
# Testa se o string resultante possui 14 caracteres
if (stringr::str_length(y) == 14) {
# Se passar a validação, transforma em data frame, pegando as seções numéricas como de um CNPJ
df <- data.frame(
s1 = stringr::str_sub(string = y, start = 1, end = 2),
s2 = stringr::str_sub(string = y, start = 3, end = 5),
s3 = stringr::str_sub(string = y, start = 6, end = 8),
s4 = stringr::str_sub(string = y, start = 9, end = 12),
s5 = stringr::str_sub(string = y, start = 13, end = 14)
)
# Realiza a interpolação dos dados para texto em formato CNPJ
stringr::str_interp("${s1}.${s2}.${s3}/${s4}-${s5}", df)
} else {
# Retorno caso o texto inserido não possua 14 caracteres
"CNPJ inválido"
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment