[英]Find & replace text not already inside an <A> tag - RegEx .Net
我正在使用聯邦注冊局(.fed)中的.NET中的XML數據,其中包含對美國法規中行政命令和各章的大量引用。
我希望能夠超鏈接到這些引用,除非它們已經在<a>
標記內(該標記由XML決定,並且通常是文檔本身內的鏈接)。
我編寫的模式是匹配和刪除前導和尾隨字符,並且不顯示它們,即使我在替換字符串中包含邊界字符也是如此:
[?!<a href="#(.*)">]([0-9]{1,2})[ ]{0,1}(U\.S\.C\.|USC)[\s]{0,1}([0-9]{1,5})(\b)[^</a>]
初始XML的示例:
<p>The Regulatory Flexibility Act of 1980 (RFA), 5 U.S.C. 604(b), as amended, requires Federal agencies to consider the potential impact of regulations on small entities during rulemaking.</p>
<p>Small entities include small businesses, small not-for-profit organizations, and small governmental jurisdictions.</p>
<p>Section 605 of the RFA allows an agency to certify a rule, in lieu of preparing an analysis, if the rulemaking is not expected to have a significant economic impact on a substantial number of small entities. Reference: <a href="#1">13 USC 401</a></p>
<ul>
<li><em>Related laws from 14USC301-345 do not apply.</em></li>
<li><a href="#2">14 USC 301</a> does apply.</li>
</ul>
如您所見,某些參考文獻包括美國法規部分的范圍(例如14 USC 301-345)或特定子節的參考范圍(例如5 USC 604(b))。 我只想鏈接到該范圍內的第一個引用,因此鏈接應以-
或(
。
如果我正確地理解了您,則我認為以下方法應該有效。
var re = new Regex(@"\d{1,2}\s?U\.?S\.?C\.?\s?\d{1,5}\b(?!</a>)");
var matches = re.Matches(text);
// matches[0].Value = 5 U.S.C. 604
// matches[1].Value = 14USC301
您甚至可以將正則表達式簡化為\\d+\\s?U\\.?S\\.?C\\.?\\s?\\d+\\b(?!</a>)
–我不確定2和5的上限很重要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.