将正则表达式匹配项存储在ruby中吗?

| 我正在使用ruby解析文件以更改数据格式。我创建了一个正则表达式,其中有三个匹配组,我想暂时将它们存储在变量中。由于所有内容都为零,我无法保存比赛内容。 这是我到目前为止所读的内容。
regex = \'^\"(\\bhttps?://[-\\w+&@#/%?=~_|$!:,.;]*[\\w+&@#/%=~_|$])\",\"(\\w+|[\\w._%+-]+@[\\w.-]+\\.[a-zA-Z]{2,4})\",\"(\\w{1,30})\'

begin
  file = File.new(\"testfile.csv\", \"r\")
  while (line = file.gets)
    puts line
    match_array = line.scan(/regex/)
    puts $&
  end
  file.close
end
这是我用于测试的一些示例数据。
\"https://mail.google.com\",\"Master\",\"password1\",\"\",\"https://mail.google.com\",\"\",\"\"
\"https://login.sf.org\",\"monster@gmail.com\",\"password2\",\"https://login.sf.org\",\"\",\"ctl00$ctl00$ctl00$body$body$wacCenterStage$standardLogin$tbxUsername\",\"ctl00$ctl00$ctl00$body$body$wacCenterStage$standardLogin$tbxPassword\"
\"http://www.facebook.com\",\"Beast\",\"12345678\",\"https://login.facebook.com\",\"\",\"email\",\"pass\"
\"http://www.own3d.tv\",\"Earth\",\"passWOrd3\",\"http://www.own3d.tv\",\"\",\"user_name\",\"user_password\"
谢谢, 低频4     
已邀请:
        这行不通:
match_array = line.scan(/regex/)
那只是使用文字\“ regex \”作为正则表达式,而不是
regex
变量中的内容。您可以将笨拙的正则表达式直接放入
scan
中,也可以创建一个Regexp实例:
regex = Regexp.new(\'^\"(\\bhttps?://[-\\w+&@#/%?=~_|$!:,.;]*[\\w+&@#/%=~_|$])\",\"(\\w+|[\\w._%+-]+@[\\w.-]+\\.[a-zA-Z]{2,4})\",\"(\\w{1,30})\')
# ...
match_array = line.scan(regex)
您可能应该使用CSV库(Ruby附带的一个:1.8.7或1.9)来解析CSV文件,然后将正则表达式应用于CSV中的每一列。这样,您将遇到较少的引用和转义问题。     

要回复问题请先登录注册