简体   繁体   中英

Find and Replace String between two values

I want to find and replace values like:

<TAG>heading<foo></foo></TAG><foo>juergen</foo>

goal:

<TAG>heading</TAG><foo>juergen</foo>

I want to remove the <foo> Tags between <TAG></TAG>

Here is my attempt:

replaceAll("</?foo\\b[^>]*>", "");

Assuming that foo is empty, you can use:

<([^/][^>]*)></\1>

This searches for an opening tag with an adjacent closing tag of the same name.

You could augment it to allow for whitespace in the middle with:

<([^/][^>]*)>\s*</\1>

Possible duplicate RegEx match open tags except XHTML self-contained tags

Otherwise, here is the regex, do not even ask me to explain, I barely know myself (this is in javascript, some corrections may need to be made for java):

var txt = "<TAG>a<foo>b</foo>c</TAG>d<foo>e</foo>f<TAG>g<foo>h</foo>i</TAG>j<TAG>k</TAG>";
var res = txt.replace(/(<TAG>.*?)<foo>.*?<\/foo>(.*?<\/TAG>)/gm,"$1$2");
//                     (   $1   )               (    $2    )
String result = searchText.replaceAll("(<f.*><.*o>)(?=<)", "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM