Todd
Todd

Reputation:

Java regex to remove all trailing numbers?

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?

Upvotes: 15

Views: 19651

Answers (3)

Danijel Mandić
Danijel Mandić

Reputation: 7

This should be the correct expression:

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

Upvotes: 0

brandon k
brandon k

Reputation: 620

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.

.

Upvotes: 37

Devon_C_Miller
Devon_C_Miller

Reputation: 16528

Assuming the value is in a string, s:

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

Upvotes: 6

Related Questions