1

params[:svn_path]このようなURLを返しています

http://svn.repos.mywebsite.com/testingtitle.documents

ここで、URL の最後の部分のみを取得する必要がありtestingtitleます。

どうやって手に入れるの?

前もって感謝します

4

7 に答える 7

3

rubyのUriモジュールが使える

uri = URI.parse("http://svn.repos.mywebsite.com/testingtitle.documents")

path = uri.path #"/testingtitle.documents"
path_with_no_slash = path.gsub("/", "") #"testingtitle.documents"
array = path_with_no_slash.split(".") #["testingtitle", "documents"]
result = array[0] #"testingtitle"
于 2012-11-15T09:46:41.913 に答える
2

使用できますFile.basename; 例えば

url = "http://svn.repos.mywebsite.com/testingtitle.documents"
ext = File.extname(url)
result = File.basename(url, ext)

basenameファイル拡張子の削除を処理するための2番目の引数。result望ましい結果を保持します。

于 2012-11-15T09:49:26.437 に答える
2

期待どおりの結果を得るには、正規表現を使用する必要があります。

これが良い例です。

于 2012-11-15T09:45:42.523 に答える
2

適切なURIパーサーを使用 -

これにより、あなたが述べたように、URL の最後の部分が得られます。

require 'uri'

url       = "http://svn.repos.mywebsite.com/testingtitle.documents"    
last_part = URI(url).path.split('/').last # => testingtitle.documents

ただし、提供した出力は、最後の部分でもう少し操作する必要があります。つまり、分割します.

last_part.split('.').first # => testingtitle

シンプルな文字列操作 -

url = "http://svn.repos.mywebsite.com/testingtitle.documents"
url.split('/').last.split('.').first # => testingtitle 
于 2012-11-15T10:04:42.257 に答える
1

これを試して:

params[:svn_path].match(/.*\.com\/(.*)\..*$/)[1]

1.9.3p194 :009 > params[:svn_path].match(/.*\.com\/(.*)\..*$/)[1]
 => "testingtitle" 
于 2012-11-15T09:44:18.180 に答える
1

URIこの URL を解析するために使用できます。

url = URI.parse('http://svn.repos.mywebsite.com/testingtitle.documents')

これらの変数を持つオブジェクトが得られます。

url.instance_variables #> [ :@scheme, :@user, :@password, :@host, :@port, :@path, :@query, :@opaque, :@registry, :@fragment, :@parser ]

path次に、次のようにコンポーネントで単純な正規表現を使用します。

url.path.match(/\w+/) #> #<MatchData "testingtitle">

これは、任意の単語文字 (/ または . を除く) の最初の出現に一致します。

于 2012-11-15T09:53:22.350 に答える
1

Regexp+groups

url = 'http://svn.repos.mywebsite.com/testingtitle.documents'
puts url.match(/com\/([a-z]+)/)[1]
#=> testingtitle
于 2012-11-15T10:21:08.437 に答える