user1966221
user1966221

Reputation: 159

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

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

Upvotes: 5

Views: 22901

Answers (3)

1218985
1218985

Reputation: 8012

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"));
    }   
}

Upvotes: 7

Johannes Kuhn
Johannes Kuhn

Reputation: 15163

Use Regex

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

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

Upvotes: 1

assylias
assylias

Reputation: 328598

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

Upvotes: 2

Related Questions