I'm trying to remove the extension from a string with the following structure:
name.stl
I found that I can use the basename
method to get the string. The problem is that I am not using the file path, and I already have the string with the name. I just need to delete the extension from the string.
It seems to me that a regular expression would be a great option to detect the dot and delete everything from it to the end.
How can I use a regex to do this on Ruby on Rails 4?
答案 0 :(得分:3)
There are several ways, here are 2, with rpartition
and a regex:
s = "more.name.stl"
puts s.sub(/\.[^.]+\z/, '') # => more.name
puts s.rpartition('.').first # => more.name
See the IDEONE demo
The rpartition
way is clear, and as for the regex, it matches:
\.
- a dot[^.]+
- one or more characters other than a dot\z
- end of string.答案 1 :(得分:3)
只需使用内置方法即可。这些将在不同的操作系统中正常工作:
filename = '/path/to/foo.bar'
File.basename(filename) # => "foo.bar"
File.extname(filename) # => ".bar"
File.basename(filename, File.extname(filename)) # => "foo"
并且,如果您需要包含目录:
File.dirname(filename) # => "/path/to"
如果你不在乎,那么一个简单的split('.')
就可以了:
'foo.bar'.split('.').first # => "foo"
或
'foo.bar'[/^[^.]+/] # => "foo"
答案 2 :(得分:2)
File.basename 'name.stl', '.stl'