java Java正则表达式删除所有尾随数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1375466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:19:12  来源:igfitidea点击:

Java regex to remove all trailing numbers?

javaregex

提问by brandon k

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?

有谁知道如何用 Java 中的正则表达式来做到这一点?

回答by brandon k

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

这应该适用于 Java String 类,其中 myString 包含用户名:

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.

这应该匹配出现在字符串末尾的任意数量的尾随数字字符 (0-9),并将它们替换为空字符串。

.

.

回答by Devon_C_Miller

Assuming the value is in a string, s:

假设值在一个字符串中,s:

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

回答by Danijel Mandi?

This should be the correct expression:

这应该是正确的表达:

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