开发者

Ruby regex group stored in a variable?

开发者 https://www.devze.com 2023-03-15 13:24 出处:网络
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

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_-]+)$'

## Open the CSV File
dat开发者_运维知识库a_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


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 your note so scan doesn't do anything useful. You want to use the Regexp class to create and store your regular expression:

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

Or (thankyou Kudo) you could use one of the regex literal forms:

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

And then pass that instance of Rexexp to note.scan:

note.scan(regex)
0

精彩评论

暂无评论...
验证码 换一张
取 消