I'm using removeNumbers to remove all numbers in a given string with the regex
"(^| )\\d+($|( \\d+)+($| )| )"
Here's the code:
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) + "\"");
}
}
}
Output :
"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"
Is there any better way to do this?
Edit :
As suggested by @mbomb007 in his previous answer, the regex "( |^)[\\d ]+( |$)" works as well:
private static String removeNumbers(String s) {
s = s.trim();
s = s.replaceAll(" +", " ");
s = s.replaceAll("( |^)[\\d ]+( |$)", " ");
return s.trim();
}