Starkers
Starkers

Reputation: 10541

Regex to get filename / exclude certain characters from the match

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.

Upvotes: 0

Views: 197

Answers (4)

hirolau
hirolau

Reputation: 13901

Alternatively, you can create subgroups in the regexp and just select the first:

str = 'name.extension'
p str[/(.*)[.]/,1] #=> name

Upvotes: 0

tihom
tihom

Reputation: 8003

Match upto the last "."

 "filen.ame.extension"[/.*(?=\.)/]
  # => filen.ame

Match upto first "."

 "filen.ame.extension"[/.*?(?=\.)/]
 # => filen

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118261

You can use File class methods File#basename and File#extname:

file= "ruby.rb"
File.basename(file,File.extname(file))
# => "ruby"

Upvotes: 3

Rohit Jain
Rohit Jain

Reputation: 213223

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).

Upvotes: 1

Related Questions