Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all tags except one with RegExp in Java

I have got the following problem. I want to delete all substrings which start with < and end with >, except the substring <back>.

Example: <apps> <up> <down> <capital> ... should be deleted, but not <back>.

I am sure this works with RegExp and String.replace(), but I don't know how.

Currently, I have figured out this:

line = line.replaceAll("<[^<]*>", "");

The problem is, that this also deletes the <back>-substring!

I hope someone of you knows a solution.

Thank's for help!

like image 956
Michael Gierer Avatar asked Dec 18 '25 13:12

Michael Gierer


1 Answers

you can use (?!<back>)<[^<]*> , line = line.replaceAll("(?!<back>)<[^<]*>", "");

(?!<back>) (negative look ahead) do not match the tag <back>

RegEx Demo

like image 123
Pavneet_Singh Avatar answered Dec 21 '25 06:12

Pavneet_Singh