Regex change href=";链接“;到href=";通知(';链接';)”;

本文关键字:quot 链接 href change Regex 通知 | 更新日期: 2023-09-27 17:59:05

Regex总是让我挠头。

在我的Windows应用商店应用程序中,需要将html内容<a href="www.example.com">替换为<a href="javascript:window.external.notify('www.example.com')">,以便在WebView中拦截导航事件。

我试过Regex.Replace(content, "<a href='"(.+)'">", "<a href='"javascript:window.external.notify('''0')'">");,但没有成功。

你能教我如何用C#做这件事吗?

Regex change href=";链接“;到href=";通知(';链接';)”;

这应该适用于您:

using System;
using System.Text.RegularExpressions;
namespace CSTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Regex re = new Regex("<a href='"(.+)'">", RegexOptions.Compiled);
            string input = "<a href='"www.example.com'">";
            string res = re.Replace(input, 
                "<a href='"javascript:window.external.notify('$1')'">");
            Console.WriteLine(res);
        }
    }
}

你几乎受够了。你唯一的问题是你对匹配的组使用了''0而不是$1

如果您喜欢调用Regex.Replace的静态版本,可以使用:

string res = Regex.Replace(input, 
    "<a href='"(.+)'">", 
    "<a href='"javascript:window.external.notify('$1')'">",
    RegexOptions.Compiled
);

我想试试这样的东西:

Regex.Replace(content, "(?<=<a href='").+(?='">)", "javascript:window.external.notify('$0')");

您应该使用$1而不是''0

我们在c#中使用$作为反向引用。