简体   繁体   English

正则表达式捕获并替换html标签之外的文本模式

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

i have some strings like "de456" "us7515", it's de/us and 3 to 10 digits. 我有一些字符串,例如“ de456”“ us7515”,它是de / us和3至10位数字。

I wish to capture all of them and replace them with an hyperlink, unless they are already inside of a html tag. 我希望捕获所有它们,并用超链接替换它们,除非它们已经在html标记内。

example: 例:

  1. should change: 应该改变:

     <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. should not change: 不应更改:

     <a href ="github.com/xxxxx/us1234> link </a> => <a href ="github.com/xxxxx/us1234> link </a> 
  3. should partially change 应该部分改变

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

I already wrote two regex: 我已经写了两个正则表达式:

to match text pattern: 匹配文本模式:

de456
us1234

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

to match text pattern inside of open html tag 匹配打开的html标记内的文本模式

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

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

so I can do 1 and 2 by using jquery regex exec and string.replace, but i don't know how to do 3. Please advise. 所以我可以通过使用jQuery正则表达式exec和string.replace来执行1和2,但是我不知道该怎么办3。 Thank you very much in advance. 提前非常感谢您。

I try this. 我尝试这个。 Please take if necessary. 如有需要请采取。

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

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

The following example is close enough, however, I don't recommend doing this in a real application. 以下示例足够接近,但是,我不建议在实际应用程序中执行此操作。

// 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