omkar sirra omkar sirra - 1 year ago 91
Java Question

How to replace any of the substrings in a string with empty substring "" (remove substring) in java

I want to allow only few substrings(allowed words) in a string. I want to remove the other substrings.

So I want to replace all the words except few words like "abc" , "def" and "ghi" etc.

I want something like this.
str.replaceAll("^[abc],"").replaceAll("^[def],"").......... (Not correct syntax)

Input: String: "abcxyzorkdefa" allowed words: {"abc","def"}

Output: "abcdef";

How to achieve this?
Thanks in Advance.

Answer Source

This is a more C-like approach, but uses Java's String.startsWith for matching patterns. The method walks along the provided string, saving matched patterns to the result string in the result they are found.

You just need to make sure that any longer patterns that contain smaller patterns come at the front of the patterns array (so "abcd" comes before "abc").

class RemoveNegated {
    public static String removeAllNegated(String s, List<String> list) {
        StringBuilder result = new StringBuilder();
        // Move along the string from the front
        while (s.length() > 0) {
            boolean match = false;
            // Try matching a pattern
            for (String p : list) {
                // If the pattern is matched
                if (s.toLowerCase().startsWith(p.toLowerCase())) {
                    // Save it
                    // Move along the string
                    s = s.substring(p.length());
                    // Signal a match
                    match = true;
                // If there was no match, move along the string
                if (!match) {
                s = s.substring(1);
        return result.toString();

    public static void main(String[] args) {
        String s = "abcxyzorkdefaef";
        s = removeAllNegated(s, Arrays.asList("abc", "def", "ghi"));

Prints: abcdef

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download