Reputation: 91
I have a situation here, I have a String
and I must to replace this <br>
to <br />
. To do it I can use replace or replace all, but some parts of the text I have <br style='font-size: 14px;'> <a><a/>
and I need replace to <br style='font-size: 14px;' /> <a><a/>
and any others similar situations in the same string;
IN
"<br> text here <br/> text here <br> text here <br style='font-size: 14px;'> <a><a/>"
EXPECTED OUT
"<br /> text here <br /> text here <br /> text here <br style='font-size: 14px;' /> <a><a/>"
Can you help me with this simple logic? replace only <br
cases
Upvotes: 0
Views: 87
Reputation: 1179
Maybe this will help. This is a regex code possibility:
package com.jesperancinha.string;
public class StringReplaceBr {
public static String closeBrTags(String a){
return a.replaceAll("<br(\\/)?([a-zA-z0-9='-:; \"]*)>", "<br$2 />");
}
}
And this is the unit test to check it up:
package com.jesperancinha.string;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class StringReplaceBrTest {
@Test
void closeSingleAlreadyClosed() {
assertThat(StringReplaceBr.closeBrTags("<br/>"))
.isEqualTo("<br />");
}
@Test
void closeSingleNotClosed() {
assertThat(StringReplaceBr.closeBrTags("<br>"))
.isEqualTo("<br />");
}
@Test
void closeSingleMixedNotClosed() {
assertThat(StringReplaceBr.closeBrTags("<br style=\"\" somethingElse=''>"))
.isEqualTo("<br style=\"\" somethingElse='' />");
}
@Test
void closeBrTags() {
assertThat(StringReplaceBr.closeBrTags("<br> text here <br/> text here <br> text here <br style='font-size: 14px;'> <a><a/>"))
.isEqualTo("<br /> text here <br /> text here <br /> text here <br style='font-size: 14px;' /> <a><a/>");
}
@Test
void closeBrTagsDoubleQuotes() {
assertThat(StringReplaceBr.closeBrTags("<br> text here <br/> text here <br> text here <br style=\"font-size: 14px;\"> <a><a/>"))
.isEqualTo("<br /> text here <br /> text here <br /> text here <br style=\"font-size: 14px;\" /> <a><a/>");
}
@Test
void closeBrSmall() {
assertThat(StringReplaceBr.closeBrTags("<br/> <br> <br/> <a><a/> <br wow=''>"))
.isEqualTo("<br /> <br /> <br /> <a><a/> <br wow='' />");
}
}
Upvotes: 1