【问题标题】:Ruby regex group stored in a variable?Ruby正则表达式组存储在变量中?
【发布时间】:2011-06-25 05:05:25
【问题描述】:

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

##### 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

【问题讨论】:

    标签: ruby regex csv regex-group


    【解决方案1】:

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

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

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

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

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

    note.scan(regex)
    

    【讨论】:

    • 你也可以使用标准的正则表达式,像这样:regex = /([\w_-]+)$/或者像这样:regex = %r{([\w_-]+)$。
    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多