我正在使用removeNumbers正则表达式删除给定字符串中的所有数字
"(^| )\\d+($|( \\d+)+($| )| )"
这是代码:
public class Regex {
private static String removeNumbers(String s) {
s = s.trim();
s = s.replaceAll(" +", " ");
s = s.replaceAll("(^| )\\d+($|( \\d+)+($| )| )", " ");
return s.trim();
}
public static void main(String[] args) {
String[] tests = new String[] {"123", "123 456 stack 789", "123 456 789 101112 131415 161718 192021", "stack 123 456 overflow 789 com", "stack 123 456 overflow 789", "123stack 456", "123 stack456overflow", "123 stack456", "123! @456#567"};
for (int i = 0; i < tests.length; i++) {
String test = tests[i];
System.out.println("\"" + test + "\" => \"" + removeNumbers(test) + "\"");
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
"123" => ""
" 123 " => ""
"123 456 stack 789" => "stack"
"123 456 789 101112 131415 161718 192021" => ""
"stack 123 456 overflow 789 com" => "stack overflow com"
"stack 123 456 overflow 789" => "stack overflow"
"123stack 456" => "123stack"
"123 stack456overflow" => "stack456overflow"
"123 stack456" => "stack456"
"123! @456#567" => "123! @456#567"
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点?
编辑:
正如@ mbomb007在之前的回答中所建议的那样,正则表达式也"( |^)[\\d ]+( |$)"可以正常工作:
private static String removeNumbers(String s) {
s = s.trim();
s = s.replaceAll(" +", " ");
s = s.replaceAll("( |^)[\\d ]+( |$)", " ");
return s.trim();
}
Run Code Online (Sandbox Code Playgroud)
AFAIU,你可以这样做:
private static String removeNumbers(String s) {
return s.replaceAll("\\b\\d+\\b", "").replaceAll(" +", " ").trim();
}
Run Code Online (Sandbox Code Playgroud)
\b\d+\b匹配构成单词的一个或多个数字。
编辑:
由于模式不能匹配字符串中的数字,例如"123! @456#567",因此可以使用正向向后查找和向前查找条件的组合:
private static String removeNumbers(String s) {
return s.replaceAll("(?<= |^)\\d+(?= |$)", " ").replaceAll(" +", " ").trim();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
255 次 |
| 最近记录: |