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

| 我在此正则表达式上遇到问题,似乎没有抓住标题(在最后一个\'。\'之后的所有内容)我已经在多个来源上测试过该正则表达式,并且它们似乎都抓住了正确的分组。扫描功能有问题吗?
##### 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
谢谢, 低频4     
已邀请:
        您没有给ѭ1分配正则表达式参数,而是给它一个普通字符串,字符串
\'([\\w_-]+)$\'
可能不会出现在
note
的任何位置,因此
scan
并没有做任何有用的事情。您想使用Regexp类创建和存储正则表达式:
regex = Regexp.new(\'([\\w_-]+)$\')
或者(谢谢工藤),您可以使用一种正则表达式文字形式:
regex = /([\\w_-]+)$/
regex = %r{([\\w_-]+)$}
然后将
Rexexp
的实例传递给
note.scan
note.scan(regex)
    

要回复问题请先登录注册