Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string replaceAll regex

Hi I want to remove certain words from a long string, there problem is that some words end with "s" and some start with a capital, basically I want to turn:

"Hello cat Cats cats Dog dogs dog fox foxs Foxs"

into:

"Hello"

at the moment I have this code but I want to improve on it, thanks in advance:

                    .replace("foxs", "")
                    .replace("Fox", "")
                    .replace("Dogs", "")
                    .replace("Cats", "")
                    .replace("dog", "")
                    .replace("cat", "")
like image 222
Kyril Khaltesky Avatar asked May 23 '26 10:05

Kyril Khaltesky


1 Answers

Try this:

String input = "Hello cat Cats cats Dog dogs dog fox foxs Foxs";
input = input.replaceAll("(?i)\\s*(?:fox|dog|cat)s?", "");

Demo

like image 67
Tim Biegeleisen Avatar answered May 25 '26 00:05

Tim Biegeleisen



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!