2014-09-26 40 views
0

我想從圖像URL字符串中刪除大小規範,但我似乎無法找到解決方案。我對正則表達式沒有太多的瞭解,所以我嘗試了[0-9x],但它只刪除了url中的所有數字,而不僅僅是維度子字符串。我只想擺脫如110x61這樣的零件。Java的正則表達式 - 忽略圖像url中的大小字符串

我想我的琴絃從這個轉換:

http://techdissected.com/wp-content/uploads/2014/09/google-fiber-rabbit-11-110x61.jpg?6da9e4 

http://techdissected.com/wp-content/uploads/2014/09/Nixeus-Headphones-Featured-Image-110x41.jpg?6da9e4 

http://techdissected.com/wp-content/uploads/2014/03/Ampedlogo_rac15a_featured-110x94.jpg?6da9e4 

這樣:

http://techdissected.com/wp-content/uploads/2014/09/google-fiber-rabbit-11.jpg?6da9e4 

http://techdissected.com/wp-content/uploads/2014/09/Nixeus-Headphones-Featured-Image.jpg?6da9e4 

http://techdissected.com/wp-content/uploads/2014/03/Ampedlogo_rac15a_featured.jpg?6da9e4 

我使用RegexPlanet測試模式,但沒有什麼,我想出來的作品... 什麼正則表達式可以解決我的問題?任何幫助,將不勝感激。刪除尾部的加分?6da9e4

我找到了一個有趣的解決方案here,但它似乎在Java中不起作用。

+0

連字符總是在子串之前嗎?即「-110x61」? – hwnd 2014-09-26 01:20:59

+0

請參閱[demo](http://www.regexr.com/39iqt) – Baby 2014-09-26 01:26:42

+0

@hwnd是的,子字符串前總是有一個連字符。 – Pkmmte 2014-09-26 23:44:10

回答

2

正則表達式-\d{1,4}x\d{1,4}

其分解爲:

- : the literal '-', followed by 
\d{1,4}: any numeric character, one to four times, followed by 
x : the literal 'x', followed by 
\d{1,4}: any numeric character, one to four times 

會爲你在Java中

工作
String input = "http://techdissected.com/wp-content/uploads/2014/09/Nixeus-Headphones-Featured-Image-110x41.jpg?6da9e4"; 
input = input.replaceAll("-\\d{1,4}x\\d{1,4}", ""); 
System.out.println(input); 
//prints: http://techdissected.com/wp-content/uploads/2014/09/Nixeus-Headphones-Featured-Image.jpg?6da9e4 
+0

謝謝,這對我來說非常合適! 有沒有辦法刪除尾部「?6da9e4」作爲這個正則表達式的一部分?有人建議我在正則表達式的末尾使用「| \\?。*」來解決這個問題,但它不起作用。 – Pkmmte 2014-09-27 01:34:56

0

不知道關於Java,但是這可能對於任何維度的工作原理:

/(-\d+x\d+)/g 
1

這個正則表達式的工作原理:

String url = "http://techdissected.com/wp-content/uploads/2014/09/google-fiber-rabbit-11-110x61.jpg?6da9e4"; 

String newUrl = url.replaceAll("-[0-9]+x[0-9]+", ""); 

System.out.println(newUrl); 

輸出:

"http://techdissected.com/wp-content/uploads/2014/09/google-fiber-rabbit-11.jpg?6da9e4" 

如果你想保持這裏的連字符-110x61使用url.replaceAll("[0-9]+x[0-9]+", "");

1

如果連字符(-)是尺寸前總是不變的,你可以使用以下內容。

url = url.replaceAll("-\\d+x\\d+", ""); 
// http://techdissected.com/wp-content/uploads/2014/09/google-fiber-rabbit-11.jpg?6da9e4 

刪除這兩個維度和後行查詢:

url = url.replaceAll("-\\d+x\\d+|\\?.*", ""); 
// http://techdissected.com/wp-content/uploads/2014/09/google-fiber-rabbit-11.jpg 
相關問題