2

I have a long string. Somewhere in the string there is a part of it that starts with &*( and then there is some text and it ends with )(*.

How can I remove this text along with the special symbols in the beginning and in the end?

Example:

Bla bla bla &*( asd asd asd )(* bla bla bla. Yadda yadda yadda &*( akls lkja )(* yadda.

I want to output

Bla bla bla bla bla bla. Yadda yadda yadda  yadda.
Unihedron
  • 10,902
  • 13
  • 62
  • 72
Kaloyan Roussev
  • 14,515
  • 21
  • 98
  • 180

3 Answers3

4

use replaceAll To do this:

    String s ="Bla bla bla &*( asd asd asd )(* bla bla bla. Yadda yadda yadda &*( akls lkja )(* yadda.Bla bla bla &*( asd asd asd )(* bla bla bla. Yadda yadda yadda &*( akls lkja )(* yadda.";
    System.out.println(s.replaceAll("\\&\\*\\(.+?\\)\\(\\*", ""));      
Jens
  • 67,715
  • 15
  • 98
  • 113
1

You can use .replaceAll():

String replaced = "Bla bla bla &*( asd asd asd )(* bla bla bla. Yadda yadda yadda &*( akls lkja )(* yadda."
                      .replaceAll("\\Q&*(\\E.+?\\Q)(*\\E", "");

Here is an online code demo!

This is the regular expression:

\Q&*(\E.+?\Q)(*\E
  • \Q Start quoting literal sequence.
    • &*( Literal character sequence "&*(".
  • \E End
  • .+? Matches more than one characters, as few as possible (lazy)
  • \Q Start quoting literal sequence.
    • )(* Literal character sequence ")(*".
  • \E End

Here is a regex demo!

Unihedron
  • 10,902
  • 13
  • 62
  • 72
0

For String manipulation I would recommend the use of StringBuilder. StringBuilder is mutable and does not create a new string for each operation

You can try the following:

final String START_INDEX = "&*(";
final String END_INDEX = ")(*";
String str = "Bla bla bla &*( asd asd asd )(* bla bla bla. Yadda yadda yadda &*( akls lkja )(* yadda.";

StringBuilder sbuild = new StringBuilder(str);
for(int start = sbuild.indexOf(START_INDEX); start != -1;){
    int end = sbuild.indexOf(END_INDEX);
    sbuild.replace(start, end + END_INDEX.length(), "");
    start = sbuild.indexOf(START_INDEX);
}

System.out.println(sbuild.toString());
Nemo
  • 587
  • 6
  • 12
  • 2
    Two notices: 1. `StringBuilder` IS mutable, it stores the added content as characters, that's why its recomended for string concatenation. 2. What if the string doesn't contain `"&*("`? Then nothing gets added to the `sbuild`. – Balázs Édes Aug 17 '14 at 07:27
  • 1. Correct it is mutable. this is what I wanted to write. I will edit my answer. 2. I understood that we always have "&*(". If this is not the case you can easily fix the code I wrote in my answer. – Nemo Sep 03 '14 at 10:42