0

How can I remove the last <br> in a string that looks like

123 Address Street<br> Queens land<br>
London<br> <br> <br>

the last
isnt neccesarely always the 5th. It can be the second, third etc

I need a regex for replaceAll() or replaceFirst()

EDIT: removed postcode

Dave819
  • 573
  • 3
  • 10
  • 14
  • 2
    Are you sure there isn't any kind of search-for-last function in Java? To be honest, regexes sound like overkill for this. – Thom Smith Mar 02 '11 at 17:31
  • Consider not using `
    ` tag at all. See css zen garden for inspiration.
    – Margus Mar 02 '11 at 17:36
  • Obligatory reference, check the answer that has nearly 5000 votes (yup, nearly 5K votes ;) http://stackoverflow.com/questions/1732348 – SyntaxT3rr0r Mar 02 '11 at 20:27

4 Answers4

10

Use String.lastIndexOf to tell you the index at which it starts, you can then cut it out yourself.

Joel
  • 29,538
  • 35
  • 110
  • 138
  • +1 for using API and not having to use regexes (which are pretty overkill as Thom Smmith says). – wkl Mar 02 '11 at 17:34
  • isn't the index the position of a single charater. lastIndexOf("
    ") returns 45 for me. is 45 the position of "<" only?
    – Dave819 Mar 03 '11 at 10:07
1
String newStr = str.replaceAll("((<br[^>*]>\\s*)+)<br[^>*]>","$1");

Note: this doesn't do exactly what you requested, instead it removes the last <br> from a group of more than one <br> tags, separated by optional whitespace. In your scenario, the result is the same, but there may be other scenarios.

If you just want to get rid of the last <br>, you can just do this:

String newStr = str.replaceFirst("(.*)<br[^>*]>","$1");
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
0
text = text.replaceAll("(?smi)<br\\s*/?>(?!\\<br).*?$", "$1")
Andrey Adamovich
  • 20,285
  • 14
  • 94
  • 132
0

one of these

"(?s)<br>(?=((?!<br>).)*$)"   or    "<br>(?=((?!<br>)[\\S\\s])*$)"