omkar sirra
omkar sirra

Reputation: 726

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.

Upvotes: 0

Views: 227

Answers (1)

Billy Brown
Billy Brown

Reputation: 2342

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
                    result.append(p);
                    // Move along the string
                    s = s.substring(p.length());
                    // Signal a match
                    match = true;
                        break;
                    }
                }
                // 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"));
        System.out.println(s);
    }
}

Prints: abcdef

Upvotes: 1

Related Questions