Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut <br/>-Tags from String end

Tags:

java

string

regex

I am currently developing a Web-Application using Java EE where I'm using a Rich-Javascript-Editor (http://www.primefaces.org/showcase/ui/editor.jsf). As the user can easily add too many linebreaks that will be convertet to linebreak-tags, I need to remove all these Tags from the end of a String.

Is there an elegant way of using Regex to accomplish this?

An example String would be:

"This is a test <b>bold</b><br/><br/>" 

Where obviously the last two tags have to be removed.

Thank you in advance for any help

Best Regards, Robert

like image 672
Robert M. Avatar asked Apr 06 '26 07:04

Robert M.


2 Answers

Something like this:

String s = "This is a test <b>bold</b><br/><br/>";
String s2 = s.replaceAll("(\\s*<[Bb][Rr]\\s*/?>)+\\s*$", "");
// s2 = "This is a test <b>bold</b>";

Note that it will also remove trailing whitespace; you can delete the final \\s* if you don't want that.

like image 71
maerics Avatar answered Apr 08 '26 20:04

maerics


Here is a simple line of Java code to remove all instances of the substring "<br/>" from the end of a string myString:

myString = myString.replaceAll("(<br/>)+$", "");
like image 45
super_aardvark Avatar answered Apr 08 '26 20:04

super_aardvark