簡體   English   中英

正則表達式捕獲並替換html標簽之外的文本模式

[英]Regex capture and replace a text pattern outside html tags

我有一些字符串,例如“ de456”“ us7515”,它是de / us和3至10位數字。

我希望捕獲所有它們,並用超鏈接替換它們,除非它們已經在html標記內。

例:

  1. 應該改變:

     <div> de485 </div> => <div> <a href = "xxx.com/de485">de485</a></div> <span> i need us1234 </span> => <span> i need <a href = "xxx.com/us1234"> us1234 </a></span> 
  2. 不應更改:

     <a href ="github.com/xxxxx/us1234> link </a> => <a href ="github.com/xxxxx/us1234> link </a> 
  3. 應該部分改變

     <a href ="github.com/xxxxx/us1234> us1234 </a> => <a href ="github.com/xxxxx/us1234> <a href = "xxx.com/us1234"> us1234 </a> </a> 

我已經寫了兩個正則表達式:

匹配文本模式:

de456
us1234

/\b(us\d{3,10}|de\d{3,10})\b/ig

匹配打開的html標記內的文本模式

<a href = "github.com/de456">

/<\s*\w.*\b(us\d{3,10}|de\d{3,10})\b.?>/ig

所以我可以通過使用jQuery正則表達式exec和string.replace來執行1和2,但是我不知道該怎么辦3。 提前非常感謝您。

我嘗試這個。 如有需要請采取。

(?<![\/])((?:de|us)[0-9]{3,10})

查看演示: http : //regex101.com/r/oS0tS3/2

以下示例足夠接近,但是,我不建議在實際應用程序中執行此操作。

// matches all 3 cases
var pattern = /([^/])((us|de)\d+)/ig;

/* 1 */
'<span> i need us1234 </span>'.replace(pattern, '$1<a href="xxx.com/$2">$2</a>');
//=> "<span> i need <a href="xxx.com/us1234">us1234</a> </span>"

/* 2 */
'<a href ="github.com/xxxxx/us1234> link </a>'.replace(pattern, '$1<a href="xxx.com/$2">$2</a>');
//=> "<a href ="github.com/xxxxx/us1234> link </a>"

/* 3 */
'<a href ="github.com/xxxxx/us1234> us1234 </a>'.replace(pattern, '$1<a href="xxx.com/$2">$2</a>');
//=> "<a href ="github.com/xxxxx/us1234> <a href="xxx.com/us1234">us1234</a> </a>"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM