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

发布于 2024-11-17 06:22:11 字数 689 浏览 7 评论 0原文

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

##### 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

稍尽春風 2024-11-24 06:22:11

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

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

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

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

然后传递 Rexexp到 note.scan

note.scan(regex)
)

或者(谢谢 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 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)
)

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文