简体   繁体   中英

Regex where XML should really be used instead, matching element with a child

Ok,

there is a mess with some code. XML/DOM should have been used, instead, for the time being a quick fix with regex on strings is required.

I have an element, with a child node of the same type.

eg.

AAA <z id="z11"> BBB <z id="z22"> CCC </z> DDD </z> endOfString.

Is there a way in regex to match the parent node in this string.

<z id="z11"> BBB <z id="z22"> CCC </z> DDD </z>

Yes, I know this all needs to be re-written, but think of this as a pure regex question.

Thanks.

Okay this sure isn't the best approach, but you say you want regex so here is the regex for this:

(<z id="[a-zA-Z0-9]+">.*?<z id="[a-zA-Z0-9]+">.*?</z>.*?</z>)

+--------------+
| Explanation: |
+--------------+

(            # indicates the start of a capturing group
<z id="      # the first part of the parent-tag
[a-zA-Z0-9]+ # matches any combination of letters and numbers for the id
">           # end of the opening parent-tag
.*?          # matches everything (ungreedy) up to the start of the child tag
<z id="      # the first part of the child-tag
[a-zA-Z0-9]+ # matches any combination of letters and numbers for the id
">           # end of the opening child-tag
.*?          # matches everything (ungreedy) up to the closing tag
</z>         # matches the closing tag (of the child)
.*?          # matches everything (ungreedy) up to the closing tag
</z>         # matches the closing tag (of the parent)

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