Mono Jamoon
Mono Jamoon

Reputation: 4607

How to replace varying text from a String

I have this HTML portion presented to me in a String.

<h1 id="Table1">Hello And welcome</h1>
<h1 id="Table2">Hello And welcome</h1>
<h1 id="Table3">Hello And welcome</h1>
<h1 id="Table4">Hello And welcome</h1>

I am trying to remove the id="*" attribute from the above string. So that the final String should contain only this:

<h1>Hello And welcome</h1>
<h1>Hello And welcome</h1>
<h1>Hello And welcome</h1>
<h1>Hello And welcome</h1>

I am using the replaceAll() method, but am unable to construct a regex to do so. Please advice.

Upvotes: 0

Views: 77

Answers (2)

Nishant
Nishant

Reputation: 55866

    String s = 
                    "<h1 id=\"Table1\">Hello And welcome</h1>"+
                    "<h1 id=\"Table2\">Hello And welcome</h1>"+
                    "<h1 id=\"Table3\">Hello And welcome</h1>"+
                    "<h1 id=\"Table4\">Hello And welcome</h1>";
    System.out.println(s.replaceAll("\\sid=\".*?\"", ""));

output

<h1>Hello And welcome</h1><h1>Hello And welcome</h1><h1>Hello And welcome</h1><h1>Hello And welcome</h1>

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336128

String result = subject.replaceAll("<h1 id=\"[^\"]*\">", "<h1>");

should work for this simple scenario.

Upvotes: 2

Related Questions