Remove data from within a String

Asked

Viewed 990 times

1

In java I am reading several lines of an HTML file and in it I have to remove some data and store in variables. And to remove this data I have to remove some tags and data that are within certain standards.

For example, to remove tags I use replaceAll("\\<.*?>", "");, but now I need to remove from String everything inside parentheses. I tried using the code replaceAll("\\(.*?)", "");, but it didn’t work out so well.

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

2 answers

1

You have to "escape" the parenthesis, otherwise it is considered a group:

"Texto qualquer (texto)".replaceAll("\\(.*\\)", "")

0

The code below has been adapted of this answer and finds texts in parentheses (including parentheses:

String str = "Teste (Java)";
String parenteses = str.substring(str.indexOf("("), str.indexOf(")") + 1);

If you need to remove all string text (including parentheses), you can create a loop:

String str = "Teste (Java)";

while (str.indexOf("(") >= 0 && str.indexOf(")") >= 0) {
    String parenteses = str.substring(str.indexOf("("), str.indexOf(")") + 1);
    str = str.replaceAll(parenteses);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.