[英]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. 我正在使用Ruby。
You can use File
class methods File#basename
and File#extname
: 您可以使用File
类方法File#basename
和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.