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

标签 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

谢谢,
LF4

最佳答案

你没有给予scan正则表达式参数,您给它一个纯字符串,并且字符串 '([\w_-]+)$' 可能不会出现在您的 note 中的任何位置所以 scan 没有做任何有用的事情。您想使用 Regexp类来创建和存储正则表达式:

regex = Regexp.new('([\w_-]+)$')

或者(谢谢 Kudo )您可以使用正则表达式文字形式之一:

regex = /([\w_-]+)$/
regex = %r{([\w_-]+)$}

然后将 Rexexp 实例传递给 note.scan:

note.scan(regex)

关于Ruby正则表达式组存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6475963/

相关文章:

sql - rails : get parent records having ZERO has_many associations

Ruby:Savon SOAP 请求收到 400 和 415 错误

ruby - 传递函数作为最终参数

mysql - 在 mysql 中再次匹配长字符串(完整邮政编码)和短字符串(邮政编码开头)

python - 如何用 pandas 打开德语 csv 文件?

C++ 写入 csv,性能

启动应用程序时 Ruby 崩溃。是环境吗?

java - 正则表达式匹配 $ 符号后跟任何单词并保留单词

Python 重新 "bogus escape error"

python - TensorFlow Iris load_csv_with_header( )