Java: removing numeric values from string

前端 未结 7 1839
心在旅途
心在旅途 2020-12-01 18:03

I have suceeded with the help of this community in removing numeric values from user input, however, my code below will only retrieve the alpha characters before the numeric

相关标签:
7条回答
  • 2020-12-01 18:26

    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.

    0 讨论(0)
  • 2020-12-01 18:29

    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
    
    0 讨论(0)
  • 2020-12-01 18:32

    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.

    0 讨论(0)
  • 2020-12-01 18:40

    This will remove all digits:

    firstname1 = firstname1.replaceAll("\\d","");
    
    0 讨论(0)
  • 2020-12-01 18:42
    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);
    
    
    
    }
    
    0 讨论(0)
  • 2020-12-01 18:43
    /*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;
         }
    }
    
    0 讨论(0)
提交回复
热议问题