1

How can i remove the last <br> from a string with replace() or replaceAll()

the <br> comes after either a <br> or a word

my idea is to add a string to the end of a string and then it'll be <br> +my added string

how can i replace it then?

124697
  • 22,097
  • 68
  • 188
  • 315
  • 2
    Does it have to be using replaceAll and regex? If so, is it homework? – GolezTrol Mar 08 '11 at 14:59
  • @GolezTrol i'd just rather is is replace or replaceAll so i dont have to add more code. i know it can be done with regex. no its not homework – 124697 Mar 08 '11 at 15:13
  • Possible duplicate: http://stackoverflow.com/questions/5171120/regex-question-how-to-remove-the-last-br-in-a-string – Wayne Mar 08 '11 at 15:17
  • @lwburk that issue is solved. it was to remove all
    escept one. this is to remove the last br
    – 124697 Mar 08 '11 at 15:25
  • @user521180 - Um, no. The question there is "How can I remove the last
    in a string", which is exactly your question.
    – Wayne Mar 08 '11 at 16:28

4 Answers4

3

Regexp is probably not the best for this kind of task. also check answers to this similar question.
Looking for <br> you could also find <BR> or <br />

String str = "ab <br> cd <br> 12";
String res = str.replaceAll( "^(.*)<br>(.*)$", "$1$2" );
// res = "ab <br> cd 12"
Community
  • 1
  • 1
bw_üezi
  • 4,483
  • 4
  • 23
  • 41
3

If you are trying to replace the last <br /> which might not be the last thing in the string, you could use something like this.

String replaceString = "<br />";
String str = "fdasfjlkds <br /> fdasfds <br /> dfasfads";
int ind = str.lastIndexOf(replaceString);
String newString = str.substring(0, ind - 1)
        + str.substring(ind + replaceString.length());
System.out.println(newString);

Output

fdasfjlkds <br /> fdasfds> dfasfads

Ofcourse, you'll have to add some checks to to avoid NPE.

Bala R
  • 107,317
  • 23
  • 199
  • 210
1

Not using replace, but does what you want without a regex:

String s = "blah blah <br>";

if (s.endsWith("<br>")) {
   s = s.substring(0, s.length() - 4);
}
Richard H
  • 38,037
  • 37
  • 111
  • 138
1

Using regex, it would be:

theString.replaceAll("<br>$", "");
Josh M.
  • 26,437
  • 24
  • 119
  • 200