0

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

Peter Parker
  • 91
  • 1
  • 10
  • 3
    Perhaps the `replaceAll` method might be of help? – GBlodgett Dec 29 '18 at 14:56
  • you need to use regexp to perform replace of your second example if you do not want to write an HTML paresre – Vladimir L. Dec 29 '18 at 15:00
  • Please bear in mind that using regexps for html may be dangerous as explained here: https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Naan Dec 30 '18 at 11:51

1 Answers1

1

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='' />");
    }

}