Java, replace strings with a string and delete everything after numbers

I have lines like:

Alian 12WE 

and

ANI1451

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

I want the result to look like this:

Alian

ANI
+5
source share
3 answers

With regex, this is 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"));
    }   
}
+7
source

You can use a regular expression to remove it 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 numbers
+2
source

Use regex

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

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

+1
source

All Articles