Skip to content

Instantly share code, notes, and snippets.

@wellingtonpgp
Created February 7, 2023 13:24
Show Gist options
  • Save wellingtonpgp/e83266df37f2d7d1c3885a6e05de6c8d to your computer and use it in GitHub Desktop.
Save wellingtonpgp/e83266df37f2d7d1c3885a6e05de6c8d to your computer and use it in GitHub Desktop.
private static String adicionarMascaraCnpfCpf(String valor) {
if (valor.length() == 14) {
Pattern pattern = Pattern.compile("(\\d{2})(\\d{3})(\\d{3})(\\d{4})(\\d{2})");
Matcher matcher = pattern.matcher(valor);
if (matcher.find()) {
return matcher.replaceAll("$1.$2.$3/$4-$5");
}
}
if (valor.length() == 11) {
Pattern pattern = Pattern.compile("(\\d{3})(\\d{3})(\\d{3})(\\d{2})");
Matcher matcher = pattern.matcher(valor);
if (matcher.find()) {
return matcher.replaceAll("$1.$2.$3-$4");
}
}
return valor;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment