<a ...=""> but not for </a> <a ...="" target="something" ...=""></a>的RegEx

时间:2013-03-04 12:27:40

标签: c# regex

请帮助重写所有没有“目标”属性的链接。

例如,文字是:

<a href="google.com" onclick="alert('Hello!!')">My Link 1</a>
<a href="my.com" class="some-class">My Link 2</a>
<a href="dot.net" target="_parent" class="some-class">My Link 3</a>
<a href="find.me" class="some-class">My Link 4</a>

需要提供文字:

<a href="google.com" onclick="alert('Hello!!')" target="_blank">My Link 1</a>
<a href="my.com" class="some-class" target="_blank">My Link 2</a>
<a href="dot.net" target="_parent" class="some-class">My Link 3</a>
<a href="find.me" class="some-class" target="_blank">My Link 4</a>

第3个链接未触及,其他链接现在具有“目标”属性。

请帮助正确表达正则表达式。我试过这个:

Regex.Replace(text, "<(a)([^>]+)(((?! target=).)*$)([^>]+)>", "<$1 target=\"_parent\" $2 $3>");

但它不起作用。

“Html Agility Pack”是不受欢迎的。

3 个答案:

答案 0 :(得分:1)

为您解决方案:

Regex _r = new Regex("<a (.+?)>");
foreach (Match m in _r.Matches(text))
{
    string Link = m.Groups[0].Value;
    if (!Link.Contains("target"))
        text = text.Replace(Link, string.Format("{0} target=\"_parent\">", Link.Substring(0, Link.Length - 1)));
}

答案 1 :(得分:1)

这可以按照要求运作:

Regex.Replace(text, "<a(((?!target=).)*)\">", "<a$1\" target=\"_parent\">")

在关闭带有"字符的开始标记之前,您关闭的每个开始锚标记都必须具有>字符,需要进行少量假设。

即。 &lt; a ...... ">我的链接&lt; / a&gt;

答案 2 :(得分:0)

这可能更容易吗? :

if (false == text.Contains("target="))
{
   Regex.Replace(text, "<(a)([^>]+)(((?! target=).)*$)([^>]+)>", "<$1 target=\"_parent\" $2 $3>");
}