开发者

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?


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"


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.


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


Using regex, it would be:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜