6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rubyでファイル名を抜き出す

Last updated at Posted at 2014-12-11

正規表現やFileクラスを用いて自分の好きな形にする。

例えば、以下のような画像URLがあった場合
http://hogehoge.co.jp/mono/actjpgs/medium/japan.jpg

・japn.jpgを取り出す


hoge.rb
file_url = "http://hogehoge.co.jp/mono/actjpgs/medium/japan.jpg"
p File.basename(file_url) # => "japan.jpg"

#Fileクラスを使用しない場合

split_file = file_url.split("/")

p split_file # => ["http:", "", "hogehoge.co.jp", "mono", "actjpgs", "medium", "japan.jpg"]

p split_file[6] # => "japan.jpg"
p split_file[-1] # => "japan.jpg"

・meduim/japn.jpgを取り出す


hoge.rb
file_url = "http://hogehoge.co.jp/mono/actjpgs/medium/japan.jpg"

# pattern1

  if matchfile = file_url.match(/medium\/.+/)
	puts matchfile # => medium/japan.jpg
  end

# pattern2

  if file_url =~ /(medium\/.+)/
	puts $1        # => medium/japan.jpg
  end

# pattern3

split_file = file_url.split("/")
p split_file[-2..-1].join("/")  # => medium/japan.jpg

=~は()をつけないと$1に値がセットされませんので注意を。

6
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?