15

I want to remove any numbers from the end of a string, for example:

"TestUser12324" -> "TestUser"
"User2Allow555" -> "User2Allow"
"AnotherUser" -> "AnotherUser"
"Test123" -> "Test"

etc.

Anyone know how to do this with a regular expression in Java?

3 Answers 3

38

This should work for the Java String class, where myString contains the username:

myString = myString.replaceAll("\\d*$", "");

This should match any number of trailing digit characters (0-9) that come at the end of the string and replace them with an empty string.

.

Sign up to request clarification or add additional context in comments.

Comments

6

Assuming the value is in a string, s:

    s = s.replaceAll("[0-9]*$", "");

Comments

0

This should be the correct expression:

(.+[^0-9])\d*$

1 Comment

If the string is "Another1Userwee a8 8 8" , then what's the regex to remove all the trailing numbers so that output would come as "Another1Userwee a"

Your Answer

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