[英]Find & Replace Multiple Instagram Urls In A String Using C#
我想在字符串中找到所有instagram网址,然后将其替换为嵌入网址。
但是我很热衷于性能,因为这可能是5到20个帖子,每个帖子最多包含6000个字符,其中包含未知数量的instagram 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网址仅在HTML属性内,这是我的第一个刺探模式:
(?<=")(https?://instagr[^">]+)
(我还为https添加了一个支票,您没有提到,但我相信它受Instagram支持。)
从理论上讲可能会出现一些误报,但比起将Peer URL的每个合法变体进行合理匹配,其效果要好得多。 (“>”检查是为了防止HTML由于某种原因而缺少结尾引号。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.