"http://www.freegreatpicture.com/files/146/26189-abstract-color-background.jpg"
この URL を部分文字列にしたいので、画像名 "26189-abstract-color-background.jpg" を取得します
どうやってするの?
こんな感じですか?
String url = "http://www.freegreatpicture.com/files/146/26189-abstract-color-background.jpg";
String file = url.substring(url.lastIndexOf('/')+1);
また
String file = new URL(url).getFile();
少し遅いですが、はるかに明確であり、URL の他の部分が必要になる可能性があるため、私は 2 番目の方法を好みます。
あなたが試すことができます
String s = "http://www.freegreatpicture.com/files/146/26189-abstract-color-background.jpg";
s = s.substring(s.lastIndexOf("/")+1);
とともに使用lastIndexOf()
しsubstring()
ます。
String path = "http://www.freegreatpicture.com/files/146/26189-abstract-color-background.jpg";
String filename = path.substring(path.lastIndexOf("/") + 1);
それを行う効率的な方法の 1 つは、正規表現を使用することです。次のようにして実現できます。
Matcher m = Pattern.compile("\\/([^\\/]+)$").matcher(link);
if (m.find())
fileName = m.group(1);
正規表現は、文字列の末尾に「/」の後に任意の数の非「/」が続くことを意味します。
ただし、部分文字列を使用する場合は、次のように簡単に行うことができます。
String fileName = link.substring(link.lastIndexOf('/')+1);
使用する
String x="http://www.freegreatpicture.com/files/146/26189-abstract-color-background.jpg";
x.substring(x.indexOf('2'))