使用 C# 查找和替换字符串中的多个 Instagram 网址

Find & Replace Multiple Instagram Urls In A String Using C#

我想在一个字符串中找到所有 instagram url,并将它们替换为嵌入 url。

但我热衷于性能,因为这可能是 5 到 20 个帖子,每个帖子最多 6000 个字符,其中的 instagram url 数量未知,需要转换。

Url 示例(可能是每个字符串中的任何一个,因此需要匹配所有

http://instagram.com/p/xPnQ1ZIY2W/?modal=true
http://instagram.com/p/xPnQ1ZIY2W/
http://instagr.am/p/xPnQ1ZIY2W/

这就是我需要用(嵌入式版本)替换它们的东西

<img src="http://instagram.com/p/xPnQ1ZIY2W/media/?size=l" class="instagramimage" />

我在考虑使用正则表达式?但这是最快和最有效的方法吗?

非常感谢任何示例。

类似于:

Regex reg = new Regex(@"http://instagr\.?am(?:\.com)?/\S*");

编辑正则表达式。但是,我会将其与 stringreader 结合起来并逐行执行。然后将字符串(修改或未修改)放入 stringbuilder:

string original = @"someotherText http://instagram.com/p/xPnQ1ZIY2W/?modal=true some other text
some other text http://instagram.com/p/xPnQ1ZIY2W/ some other text
some other text http://instagr.am/p/xPnQ1ZIY2W/ some other text";

StringBuilder result = new StringBuilder();

using (StringReader reader = new StringReader(original))
{
    while (reader.Peek() > 0)
    {
        string line = reader.ReadLine();
        if (reg.IsMatch(line))
        {
            string url = reg.Match(line).ToString();
            result.AppendLine(reg.Replace(line,string.Format("<img src=\"{0}\" class=\"instagramimage\" />",url)));
        }
        else
        {
            result.AppendLine(line);
        }
   }
}

Console.WriteLine(result.ToString());

你的意思是这样?

class Program
{
    private static Regex reg = new Regex(@"http://instagr\.?am(?:\.com)?/\S*", RegexOptions.Compiled);
    private static Regex idRegex = new Regex(@"(?<=p/).*?(?=/)",RegexOptions.Compiled);

    static void Main(string[] args)
    {
        string original = @"someotherText  http://instagram.com/p/xPnQ1ZIY2W/?modal=true some other text
some other text http://instagram.com/p/xPnQ1ZIY2W/ some other text
some other text http://instagr.am/p/xPnQ1ZIY2W/ some other text";

        StringBuilder result = new StringBuilder();

        using (StringReader reader = new StringReader(original))
        {
            while (reader.Peek() > 0)
            {
                string line = reader.ReadLine();
                if (reg.IsMatch(line))
                {
                    string url = reg.Match(line).ToString();
                    result.AppendLine(reg.Replace(line, string.Format("<img src=\"http://instagram.com/p/{0}/media/?size=1\" class=\"instagramimage\" />", idRegex.Match(url).ToString())));
                }
                else
                {
                    result.AppendLine(line);
                }

            }
        }

        Console.WriteLine(result.ToString());



    }
}

精心制作和编译的正则表达式很难被​​打败,尤其是因为您要进行替换,而不仅仅是搜索,但您应该进行测试以确定。

如果 Instagram URL 在 HTML 属性中,这是我的第一次尝试要查找的模式:

(?<=")(https?://instagr[^">]+)

(我也添加了 https 的检查,你没有提到,但我相信 Instagram 支持。)

一些误报在理论上是可能的,但它会比迂腐地匹配 Instagram 的每个合法变体 URL 表现得更好。 (“>”检查只是为了防止 HTML 由于某种原因缺少结束引号。)