【问题标题】:regex remove dynamic string and keep the rest [closed]正则表达式删除动态字符串并保留其余部分[关闭]
【发布时间】:2013-10-25 14:16:43
【问题描述】:

我需要从中删除:http://example.com/media/catalog/product/cache/1/thumbnail/56x/9df78eab33525d08d6e5fb8d27136e95/i/m/images_3.jpgproduct/ 和 /i 之间的所有内容,并使用正则表达式或 c# 保留 http://example.com/media/catalog/product/i/m/images_3.jpg。这些是爬虫应用程序中的选项。 请帮忙。

【问题讨论】:

  • i/m/ 会保持不变吗?能改变吗?到目前为止,您是否尝试过任何代码?如果是,请也发布代码。
  • 是的,它总是像 i/m

标签: c# regex web-crawler


【解决方案1】:
var input = "http://example.com/media/catalog/product/cache/1/thumbnail/56x/9df78eab33525d08d6e5fb8d27136e95/i/m/images_3.jpg";
var re = new Regex("^(.+/product)/.+(/i/.+)$");
var m = re.Match(input);
if (!m.Success) throw new Exception("does not match");
var result = m.Groups[1].Value + m.Groups[2].Value;
//result = "http://example.com/media/catalog/product/i/m/images_3.jpg"

【讨论】:

  • 几分钟后我也会检查你的
  • 这也很好用。谢谢。
  • 另外,它是唯一可以按照陈述的方式回答您的问题的答案(使用正则表达式并将字符串增加到“/i”),而无需假设一定的长度(未指定)在你的问题中)
【解决方案2】:
string str = "http://example.com/media/catalog/product/cache/1/thumbnail/56x/9df78eab33525d08d6e5fb8d27136e95/i/m/images_3.jpg";
int prodIndex = str.IndexOf("/product/");
int iIndex = str.IndexOf("/i/");
string newStr = str.Substring(0, prodIndex + "/product/".Length)
              + str.Substring(iIndex + 1);

这是一个使用正则表达式的更通用示例,它只查找 32 个字符散列之后的部分,而不是假设它是 /i/

string str = "http://example.com/media/catalog/product/cache/1/thumbnail/56x/9df78eab33525d08d6e5fb8d27136e95/i/m/images_3.jpg";
var match = Regex.Match(str, @"(.*/product/).*/.{32}/(.*)");
var newStr = match.Groups[1].Value + match.Groups[2].Value;

【讨论】:

  • 我认为第一个会更通用,因为我不t know if the hash will always contain that nr of chars. Ill 尝试你的方法。谢谢
  • -1 因为在第二个代码部分中,您正在硬编码一定的长度,而不是像指定的问题那样查找字符“/i”。第一个代码部分没有硬编码长度,但不使用问题中指定的正则表达式
  • 哈希通常是固定长度的,所以我认为确保它是 32 个字符长是一个比下一部分总是/i/ 更好的假设。根据我对此类 URL 的了解,i 部分可以是任何字符,而长哈希将保持相同的长度。
  • 根据 URL 的实际格式,您可能会根据哈希的长度或/././.+ 模式来获取最后两个文件夹或其他内容。不过,根据他告诉我们的信息,我想我给出了一个很好的猜测。 =)
  • 只要它有效,我不会t really care about your fight here. All the solutions you 2 have provided work, so Ill 将第一个答案标记为正确。谢谢你们,我也不要t want to be a judge in here. First wins, and thats。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 2012-08-13
相关资源
最近更新 更多