Reputation: 159
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
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
Reputation: 15163
Use Regex
"Alian 12WE".split("\\d")[0] // Splits the string at numbers, get the first part.
Or replace "\\d.+$"
with ""
Upvotes: 1
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 digitsUpvotes: 2