Ruby正则表达式组存储在一个变量中?

LF4*_*LF4 2 ruby regex csv regex-group

我有这个正则表达式的问题它似乎没有抓住标题(在最后''之后的所有内容.)我已经在多个来源上测试了正则表达式,他们似乎都抓住了正确的分组.扫描功能是我做错了吗?

##### data.csv file #####
## Web_Sites.Shopping.Newegg,...
## Web_Sites.Shopping.Newegg_Secure,...
## Web_Sites.Shopping.O'Reilly_Books,...
## Web_Sites.Shopping.PackageTrackr,...
#####

## Grab the title from the list
regex = '([\w_-]+)$'

## Open the CSV File
data_file = CSV.open("data.csv", "r")

## Set the file we will append the data.
my_file = File.new("titles.csv", 'a')

## For each line in the data file, get the correct title
data_file.each do |data|
   note = data[0]
   title = note.scan(regex)
   my_file.print "#{note} : #{title}"
end
Run Code Online (Sandbox Code Playgroud)

谢谢你,
LF4

mu *_*ort 5

你没有提供scan一个正则表达式参数,你给它一个普通的字符串,字符串'([\w_-]+)$'可能不会出现在你的任何地方,note所以scan没有做任何有用的事情.您想使用Regexp类来创建和存储正则表达式:

regex = Regexp.new('([\w_-]+)$')
Run Code Online (Sandbox Code Playgroud)

或者(thankyou Kudo)您可以使用其中一种正则表达式文字形式:

regex = /([\w_-]+)$/
regex = %r{([\w_-]+)$}
Run Code Online (Sandbox Code Playgroud)

然后将该实例传递Rexexpnote.scan:

note.scan(regex)
Run Code Online (Sandbox Code Playgroud)

  • 你也可以使用标准的正则表达式,如下所示:`regex = /([\ w _-] +)$ /`或者像这样:`regex =%r {([\ w _-] +)$`. (3认同)