我想在一个字符串中找到所有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*");
编辑正则表达式。但是,我会将其与字符串阅读器结合使用并逐行执行。然后将字符串(修改与否)放入字符串生成器中:
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 由于某种原因缺少结束引号。