user1725619
user1725619

Reputation:

Looking for one-liner to remove multiple sub-string

I have a string with contains two sub-strings:

sub_string1 = 123;
sub_string2 = 456;

full_string = "456".concat(sub_string1).concat(sub_string2);

Later I want to remove sub_string1 and sub_string2 from full_string.

My current method to do is cumbersome:

String Removed1 = full_string.replace(sub_string1, "");
String Removed2 = Removed1.replace(sub_string2, "");

I am looking for a one liner to solve this problem, any suggestions?

Upvotes: 1

Views: 59

Answers (3)

John Bollinger
John Bollinger

Reputation: 180048

Your code is suffers from the problem that removal of the first substring could conceivably create appearances of the second that did not previously exist, and which would then be removed in the second step. Any approach that performs the removals in two steps suffers from this issue.

If you want to remove only those appearances of the two substrings that appear in the original full string, then you have to perform both removals in one pass, and that is most easily accomplished with a regex-based approach. It can be a bit tricky to construct such a regex if the substrings may contain regex metacharacters, but it can be done:

String removed = full_string.replace(
        Pattern.quote(substring1) + "|" + Pattern.quote(substring2), "");

I present it as a single statement spanning two lines, but the number of lines is simply a matter of whitespace. If the number of source lines were really what you cared about then you could just concatenate the lines of your original code into one.

Note that the above still isn't necessarily perfect, in that it may or may not do what you want in the event that the tail of one substring matches the beginning of the other.

Upvotes: 0

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

You can use regex to remove multiple occurence of string using Matches either token

String sub_string1 = "123";
String sub_string2 = "456";

String finals = "456df123".replaceAll(sub_string1 +"|"+sub_string2 , "");
//or
//String finals = "456df123".replaceAll("456|123" , "");
System.out.println(finals);

result:

df

Upvotes: 2

bgstech
bgstech

Reputation: 674

You can combine them like this:

String Removed = full_string.replace(sub_string1,"").replace(sub_string2, "");

Upvotes: 0

Related Questions