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
I'm having issues with this regex it doesn't seem to grab the titles (everything after the last '.' ) I've tested the regex on multiple sources and they all seem to grab the correct grouping. Is it something with the scan function that I am doing wrong?
##### 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_-]+)
Thank you,
LF4
## 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
Thank you,
LF4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您没有提供
扫描
正则表达式参数,您给它一个纯字符串,并且字符串'([\w_-]+)$'
可能不会出现在note
中的任何位置,因此扫描
没有做任何有用的事情。您想要使用 Regexp 类来创建和存储正则表达式:或者(谢谢 Kudo)您可以使用正则表达式文字形式之一:
然后传递
Rexexp到
note.scan
:You're not giving
scan
a regular expression argument, you're giving it a plain string and the string'([\w_-]+)$'
probably doesn't appear anywhere in yournote
soscan
doesn't do anything useful. You want to use the Regexp class to create and store your regular expression:Or (thankyou Kudo) you could use one of the regex literal forms:
And then pass that instance of
Rexexp
tonote.scan
: