Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to invert a call to String's replaceAll method?

For example...

String s = "abcxyzabcxyz";
s.replaceAll("xyz", "---");

This would normally give me "abc---abc---". How would I get it to give me "---xyz---xyz" instead?

like image 663
Ogen Avatar asked Jan 18 '26 14:01

Ogen


1 Answers

String#replaceAll accepts a regex, if I understood you correctly, you can use:

s.replaceAll("[^xyz]", "---")

Explanation:

[^xyz] means any character that's not one of "x", "y" or "z".

In order to negate "xyz" as a series, use:

^(?!.*xyz).*$
like image 100
Maroun Avatar answered Jan 20 '26 03:01

Maroun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!