5

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
1
  • Use regular expression to search the first index of number and then use substring(0,index) .. google it on how to use regex in java and substring method. Enjoy coding :) Commented Mar 9, 2013 at 17:11

3 Answers 3

7

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"));
    }   
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

Use Regex

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

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

2 Comments

Add .trim() to remove trailing spaces
Look at the example output: Alian

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.