Well there are of course methods to make this working. For example replace
accepts regex which is capable of negating by using negative lookahead (How to negate specific word in regex?). Or you can manually traverse the input etc.
Solution
However there is a much more easy solution. If you want to delete everything which is not foo
in your input
test foo bar 123 test
then the result can either be completely empty (if foo
is not contained) or only foo
(if it was contained). So simply check for your needle being present:
public String deleteAllExceptFirst(String input, String needle) {
if (input.contains(needle)) {
return needle;
} else {
return "";
}
}
Multiple instances
Note that if you want to preserve multiple foo
occurrences you need additional work. Just count how many times foo
is contained and then print it concatenated:
public String deleteAllExcept(String input, String needle) {
StringBuilder sb = new StringBuilder();
// Find all occurrences
Pattern needlePatt = Pattern.compile(needle);
Matcher matcher = needlePatt.matcher(input);
while (m.find()) {
// Build the result
sb.append(needle);
}
return sb.toString();
}
For the test input
test foo bar 123 test foo foo bar foo
this yields
foofoofoofoo