Regular expression

Asked

Viewed 2,696 times

3

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

I managed to get ("-") out of the zip code

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

there in the case of phone has ()#####-#### how can I remove?

  • In short, you want only the numbers?

  • Yes only the numbers, @Randrade

2 answers

7


You can use the expression [^0-9] to obtain 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 it working on Ideone.

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 ]", ""));

Using negation and different values of numeric digits ( d), all different characters of numbers will be removed from the string. This avoids the need to keep adding restrictions to hyphens, parentheses, dots, etc...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.