Petr
Petr

Reputation: 1

Java remove dynamic substring from string

I need to remove dynamic substring from string. There is a few similar topic of this theme, but noone of them helped me. I have a string e.g.:

product test1="001" test2="abc" test3="123xzy"

and i need output:

product test1="001" test3="123xzy"

I mean I need remove test2="abc". test2 is an unique element and can be placed anywhere in original string. "abc" is dynamic variable and can have various length. What is the fastest and the most elegant solution of this problem? Thx

Upvotes: 0

Views: 885

Answers (1)

assylias
assylias

Reputation: 328598

You can use a regular expression:

String input = "product test1=\"001\" test2=\"abc\" test3=\"123xzy\"";
String result = input.replaceAll("test2=\".*?\"\\s+", "");

In substance: find a substring like test2="xxxxxx", optionally followed by some spaces (\\s+) and replace it with nothing.

Upvotes: 2

Related Questions