Here's my file:
name.extension
And here's my regex:
.*[.]
However this matches the filename and the period:
#=> "filename."
How can I exclude the period in order to achieve:
#=> "filename"
I'm using Ruby.
You can use File
class methods File#basename
and File#extname
:
file= "ruby.rb"
File.basename(file,File.extname(file))
# => "ruby"
You just need a negated character clas:
^[^.]*
This will match everything, from the beginning of the string till it finds a period (but not include it).
Match upto the last "."
"filen.ame.extension"[/.*(?=\.)/]
# => filen.ame
Match upto first "."
"filen.ame.extension"[/.*?(?=\.)/]
# => filen
Alternatively, you can create subgroups in the regexp and just select the first:
str = 'name.extension'
p str[/(.*)[.]/,1] #=> name
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.