2013-10-25 37 views
1

我需要從這裏刪除:http://example.com/media/catalog/product/cache/1/thumbnail/56x/9df78eab33525d08d6e5fb8d27136e95/i/m/images_3.jpg產品/和/我之間的一切,並保持http://example.com/media/catalog/product/i/m/images_3.jpg使用正則表達式,或c#。這些是搜尋器應用程序中的選項。 請幫忙。正則表達式刪除動態字符串,並保留其餘

+1

請問'I /米/'是恆定的?它可以改變嗎?你到目前爲止是否嘗試過任何代碼?如果是,請張貼代碼。 – unlimit

+0

是的,它會一直像我/我 – geryjuhasz

回答

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" 
+1

我也會在幾分鐘內檢查你的。 – geryjuhasz

+1

這也工作得很好。謝謝。 – geryjuhasz

+0

此外,它是唯一的答案,它回答你的問題的方式(使用正則表達式,並獲得字符串「/我」)沒有假設一定的長度(這是沒有在你的問題中指定) – JoelFan

0
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); 

下面是使用正則表達式更通用的例子,那只是看起來不是假定這將是/i/爲32個字符的散列後的部分,:

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; 
+0

我認爲第一個將是更通用的,因爲我不知道如果哈希將始終包含該字符的nr。我會試試你的方法。謝謝 – geryjuhasz

+0

完美,謝謝! – geryjuhasz

+0

-1因爲在第二個代碼部分中,您正在對特定長度進行硬編碼,而不是像指定的問題那樣查找字符「/ i」。第一個代碼段沒有硬編碼的長度,但沒有使用正則表達式中指定的正則表達式 – JoelFan

相關問題