简体   繁体   English

RegExp查找标签和变量

[英]RegExp to find tag and variable

Can you please correct my RegExp so it will work? 您能否更正我的RegExp使其正常工作? I need to check if the string I want to replace is not surrounded by an a tag. 我需要检查我要替换的字符串是否没有被标签包围。

var re = new RegExp("<a\b[^>]*>"+variable+"<\/a>","gi");

You must capture all links before and replace them by themselves: 您必须先捕获所有链接并自行替换它们:

var variable = "os";
var yourstring= "sdfsdlkjfsd <a href=blux> os</a> sdfsdflkjsdf os";

var re = new RegExp("(<a\\b[^>]*>(?:[^<]+|<(?!/a>))*</a>)|("+variable+")","gi");

function replacer(match, p1, p2){
    var replacement = "glups";
    return (p1)? p1 : replacement;
};
var result = yourstring.replace(re, replacer);
console.log(result);

Pattern detail: 图案细节:

(?:[^<]+|<(?!/a>))* describes the content between "a" tags, and means all that is not a < or a < that is not the part of the closing "a" tag (?:[^<]+|<(?!/a>))*描述之间的“a”的标签的内容的装置,以及所有这不是一个<<不是闭合的部分“A”标签

(?:          # open a non capturing group
    [^<]+    # all characters except < one or more times
  |          # OR
    <(?!/a>) # < not followed by "/a>"
)*           # close the non capturing group and repeat zero or more times

您需要将\\\\b的反斜杠加倍,以使其通过\\b到达正则表达式:

var re = new RegExp("<a\\b[^>]*>"+variable+"<\/a>","gi");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM