Regular expression

3

I have a question about how can I make a regular expression to remove phone masks, cpf, cnpj.

I was able to remove ("-") from the CEP

String[] cepText = edtCep.getText().toString().split("-");

ai in the case of phone has ()#####-#### how can I do to remove?

    
asked by anonymous 20.12.2016 / 12:07

2 answers

4

You can use the expression [^0-9] to get only the numbers.

An example would be this:

    String tel = "(99) 9 9999-9999";
    String cpf = "111.111.111-11";
    String cnpj = "11.111.111/0001-11";

    System.out.println("Tel: " + tel.replaceAll("[^0-9]", ""));
    System.out.println("CPF: " + cpf.replaceAll("[^0-9]", ""));
    System.out.println("CNPJ: " + cnpj.replaceAll("[^0-9]", ""));

See working on Ideone.

    
20.12.2016 / 12:32
3

If your intention is to leave the string only with the numbers use:

    String fone = "(51)9994-5845";
    String cpf = "025.454.644-55";
    String cnpj = "02.321.351/0001-35";

    System.out.println(fone.replaceAll("[^\d ]", ""));
    System.out.println(cpf.replaceAll("[^\d ]", ""));
    System.out.println(cnpj.replaceAll("[^\d ]", ""));

With the use of negation and different values of numeric digits (^ \ d), all characters other than numbers will be removed from the string. This avoids the need to be adding constraints to hyphen, parentheses, periods, etc ...

    
20.12.2016 / 12:26