Search code examples
javaregexswingjeditorpane

Regular Expression, JEditorPane, Self-closing tags


I'm am using JEditorPane to render basic HTML. But it renders self-closing tags incorrectly, specifically br tags, e.g. <br /> is bad but <br> is good. I would like to use String.replaceAll(regex, "<br>") to fix the HTML, where regex is a regular expression matching any self-closing br tag with case-insensitivity and zero to infinity number of spaces between the "r" and the "/" (e.g., <br/>, <BR/>, <br />, <Br     />, etc.).

Thanks to any regular expression experts who can solve this!


Solution

  • You can use the regex:

    <[bB][rR]\s*/>
    
    • < : To match a literal <
    • [bB] : A char class that matches either b or B
    • [rR] : A char class that matches either r or R
    • \s : Any one white space
    • \s* : zero or more white spaces.

    If you want to allow only a space for a white space you can use:

    <[bB][rR] */>