0

I have a string that I define as

String string = "<html><color=black><b><center>Line1</center><center>Line2</center></b></font></html>";

that I apply to a JButton to get 2 lines of text on it, and that works perfectly. When I call the JButton.getText() method, it returns the whole string. What I want is to take the string it returns, and get the string "Line1Line2" from it. (So I want to remove all the HTML code and just get the text that appears on the screen.) I have tried using something like

if(string.contains("<html>"))
    {
        string.replace("<html>", "");
    }

and then doing the same thing for all the other "<(stuff)>", but if I then print the string, I still get the whole thing. I think using regular expressions is a better way than to manually remove all the "<(stuff)>", but I don't know how.

Any help would be most appreciated!

3 Answers 3

3

string.replace() doesn't modify the string: a String is immutable. It returns a new string where the replacement has been done.

So your code should be

if (string.contains("<html>")) {
    string = string.replace("<html>", "");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks (again)! That's what I needed. That's twice I owe you now :)
1

String is immutable, so String#replace does not change the String but rather returns the changed String.

string = string.replace("<html>", "");

and so on should do the thing.

Comments

1

String also has a replaceAll() method.

you could try string.replaceAll("<.*?>", "");

Also keep in mind that Strings in java are immutable and this operation will return a new String with your result

Comments

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.