Java:从字符串中删除数值

2022-09-01 12:20:23

在这个社区的帮助下,我成功地从用户输入中删除了数值,但是,我下面的代码只会检索已删除数字之前的字母字符:

import java.util.Scanner;

public class Assignment2_A {

    public static void main(String[] args) {
        Scanner firstname = new Scanner(System.in);
        String firstname1 = firstname.next();
        firstname1 = firstname1.replaceAll("[^A-Z]","");
        System.out.println(firstname1);
    }
}

例如,如果用户输入 = S1234am,我只得到:S。如何检索字符串中的其余字符?


答案 1

这将删除所有数字:

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

答案 2

您可以使用:

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

这将从字符串 中删除所有数值。firstName1

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