124697
124697

Reputation: 21893

regex how do i remove the last "<br>" in a string

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?

Upvotes: 1

Views: 2234

Answers (4)

Josh M.
Josh M.

Reputation: 27783

Using regex, it would be:

theString.replaceAll("<br>$", "");

Upvotes: 1

bw_&#252;ezi
bw_&#252;ezi

Reputation: 4564

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"

Upvotes: 3

Bala R
Bala R

Reputation: 108947

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.

Upvotes: 3

Richard H
Richard H

Reputation: 39055

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);
}

Upvotes: 1

Related Questions