Java, replace string numbers with blankstring and remove everything after the numbers

22,105

Solution 1

With a regex, it's pretty simple:

public class Test {

    public static String replaceAll(String string) {
        return string.replaceAll("\\d+.*", "");
    }

    public static void main(String[] args) {
        System.out.println(replaceAll("Alian 12WE"));
        System.out.println(replaceAll("ANI1451"));
    }   
}

Solution 2

You could use a regex to remove everyting after a digit is found - something like:

String s = "Alian 12WE";
s = s.replaceAll("\\d+.*", "");
  • \\d+ finds one or more consecutive digits
  • .* matches any characters after the digits

Solution 3

Use Regex

"Alian 12WE".split("\\d")[0] // Splits the string at numbers, get the first part.

Or replace "\\d.+$" with ""

Share:
22,105
user1966221
Author by

user1966221

Updated on March 28, 2020

Comments

  • user1966221
    user1966221 about 4 years

    I have strings like:

    Alian 12WE 
    

    and

    ANI1451
    

    Is there any way to replace all the numbers (and everything after the numbers) with an empty string in JAVA?

    I want the output to look like this:

    Alian
    
    ANI
    
  • asifsid88
    asifsid88 about 11 years
    Add .trim() to remove trailing spaces
  • Johannes Kuhn
    Johannes Kuhn about 11 years
    Look at the example output: Alian