简体   繁体   中英

Capture opening but not the closing tag

I want to segment a parent block, while capturing nested tags along each segment's text:

(?<tag>.)(?: href="(?<url>.+?)")?>(?<text>.+?)<

it works, but I want the "tag" to be empty in segments that aren't wrapped in a tag, however with the current reg., these capture the preceding segment's closing tag...:(

Live sample: https://regex101.com/r/UEZAaw/3/

The result set I would like to obtain, note that item 2 and 4 should have null for the tag:

{
   "0":{
      match: "p>The <",
      tag: "p",
      url: null,
      text: "The "
   },
   "1":[
      match: "a href=\"https://www.legislation.gov.uk/ukpga/2010/23/contents\">UK Bribery Act<",
      tag: "a",
      url: "https://www.legislation.gov.uk/ukpga/2010/23/contents",
      text: "UK Bribery Act"
   ],
   "2":[
      match: "/a> (“the Act”) received Royal Assent in April 2010 and came into ... <",
      tag: null
      url: null,
      text: " (“the Act”) received Royal Assent in April 2010 and came into ... "
   ],
   "3":[
      match: "a href=\"http://www.oecd.org/daf/anti-bribery/ConvCombatBribery_ENG.pdf\">OECD anti-bribery Convention<",
      tag: "a",
      url: "http://www.oecd.org/daf/anti-bribery/ConvCombatBribery_ENG.pdf",
      text: "OECD anti-bribery Convention"
   ],
   "4":[
      match: "/a>. The Act outlined four prime offences, including the introduction ... <",
      tag: null,
      url: null,
      text: ". The Act outlined four prime offences, including the introduction ... "
   ],
   "5":[
      match: "b>rest is history<",
      tag: "b",
      url: null,
      text: "rest is history"
   ]
   ...
}

Spent a few good hours, haven't figured it out, would really appreciate your suggestions.

我认为这是有效的,基于我在regex101MATCH INFORMATION框中看到的内容

/(?:(?<tag>(?<!\/).)|(?:\/.))(?: href="(?<url>.+?)")?>(?<text>.+?)</gm

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