这场比赛的正则表达式

时间:2013-07-29 11:45:49

标签: c# asp.net regex

所以我有样本网址http://citrine.rcd.dev:8080/image/1582_125x125.jpg

它是用代码构建的:

    public string GetDerivativeUrl(long imageId, bool preserveTransparency, DerivativeSize size, bool allowCache, string designTags, int quality)
    {
        string tags = (designTags == null || designTags.Trim().Length == 0) ? "" : designTags;
        string imageFormat = (preserveTransparency) ? "png" : "jpg";
        if (quality > 0)
            return String.Format("{0}/image/{4}{1}_{2}.{3}?qv={5}", GetUrlPrefix(imageId, allowCache), imageId, size.GetPixelSize(), imageFormat, tags, quality);
        return String.Format("{0}/image/{4}{1}_{2}.{3}", GetUrlPrefix(imageId, allowCache), imageId, size.GetPixelSize(), imageFormat, tags);
    }

我想从http://citrine.rcd.dev:8080/image/1582.jpg

获取http://citrine.rcd.dev:8080/image/1582_125x125.jpg

我该怎么做?

2 个答案:

答案 0 :(得分:1)

使用System.Uri从路径中获取文件名部分,然后将"_.*?\."替换为"."

答案 1 :(得分:1)

你可以这样做,而不是使用正则表达式。

string url = @"http://citrine.rcd.dev:8080/image/1582_125x125.jpg";
int index = url.LastIndexOf('_');
if (index != -1)
   url = url.Substring(0, index) + Path.GetExtension(url);