Java: removing numeric values from string

This will remove all digits:

firstname1 = firstname1.replaceAll("\\d","");

You can use:

firstname1 = firstname1.replaceAll("[0-9]","");

This will remove all numeric values from String firstName1.

    String firstname1 = "S1234am";
    firstname1 = firstname1.replaceAll("[0-9]","");
    System.out.println(firstname1);//Prints Sam

Your regular expression [^A-Z] is currently only configured to preserve upper-case letters. You could try replacing it with [^A-Za-z] to keep the lower-case letters too.


How to remove numeric values from a string:

to do this it will be enough

str.replaceAll("[^A-Za-z]","");

but what if your string contain characters like:

String str = "stackoverflow elenasys +34668555555 # Пивоварова Пивоварова հայեր հայեր አማሪኮ     አማሪኮ kiểm tra kiểmtra ตรวจสอบ ตรวจสอบ التحقق من التحقق من";

most of the characters will be removed too, so this is a better option:

str = str.replaceAll("[\\d.]", "");

to remove all numeric values and get as result:

stackoverflow elenasys + # Пивоварова Пивоварова հայեր հայեր አማሪኮ     አማሪኮ kiểm tra kiểmtra ตรวจสอบ ตรวจสอบ التحقق من التحقق من

Your regex:

[^A-Z]

matches anything which is not an uppercase letter.

Which means any lowercase letter will match too.

You should probably use:

[^A-Za-z]

as a regex instead.

Note also that this will not account for anything other than ASCII. It may, or may not, be what you want.