Java: removing numeric values from string

懵懂的女人 提交于 2019-11-27 14:37:34

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.

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

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.

public static void main(String[] args) {
    String address = "34732483dhshdsdhajsa8ejdsdd";
    char[] chars = address.toCharArray();
    String aString = "";

    for (int i = 0; i < chars.length; i++) {
        if (!Character.isDigit(chars[i])) {
            aString =aString + chars[i]; 


        }

    }System.out.println(aString);



}
/*Remove numbers from given specific string*/
public class NewClass6 {
public static void main(String[] args){
    String s= "hello647hi74joke";
    char[] ch=s.toCharArray();
    System.out.println("Result = "+getString(ch));
 }
 static String getString(char[] ch){
   int m = 0;
   char[] chr=new char[50];
   char[] k = {'0','1','2','3','4','5','6','7','8','9'};
   for(int i = 0 ; i < ch.length ; i++){
       for(int j = 0 ; j < k.length ; j++){  
           if(ch[i]==k[j]){
               m--;
               break;
           }else{
               chr[m]=ch[i];
           }
       }
       m++;
     }
     String st = String.valueOf(chr);
     return st;
     }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!