[英]Java, replace string numbers with blankstring and remove everything after the numbers
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? 有没有办法用JAVA中的空字符串替换所有数字(以及数字后面的所有内容)?
I want the output to look like this: 我希望输出看起来像这样:
Alian
ANI
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"));
}
}
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 \\\\d+
找到一个或多个连续数字 .*
matches any characters after the digits .*
匹配数字后面的任何字符 Use Regex 使用正则表达式
"Alian 12WE".split("\\d")[0] // Splits the string at numbers, get the first part.
Or replace "\\\\d.+$"
with ""
或者用"\\\\d.+$"
替换"\\\\d.+$"
""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.