0

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

2
  • 1
    Split the String by spaces and look in the resulting String[] for the one that startsWith("test2") Commented Jun 26, 2018 at 9:35
  • You can use regex to remove str.replaceAll("test2=\"\\w+\"", ""); Commented Jun 26, 2018 at 9:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. It helped me a lot. Really nice solution by using RegExp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.