【发布时间】:2012-12-19 04:55:49
【问题描述】:
我正在构建一个爬虫来搜索我的文件系统以查找包含特定信息的特定文档。然而,正则表达式部分让我有点困惑。我的桌面上有一个包含“teststring”的测试文件和一个测试信用卡号“4060324066583245”,下面的代码将正常运行并找到包含teststring的文件:
require 'find'
count = 0
Find.find('/') do |f| # '/' for root directory on OS X
if f.match(/\.doc\Z/) # check if filename ends in desired format
contents = File.read(f)
if /teststring/.match(contents)
puts f
count += 1
end
end
end
puts "#{count} sensitive files were found"
运行此程序可确认爬虫正在工作并正确找到匹配项。但是,当我尝试运行它以查找测试信用卡号时,它找不到匹配项:
require 'find'
count = 0
Find.find('/') do |f| # '/' for root directory on OS X
if f.match(/\.doc\Z/) # check if filename ends in desired format
contents = File.read(f)
if /^4[0-9]{12}(?:[0-9]{3})?$/.match(contents)
puts f
count += 1
end
end
end
puts "#{count} sensitive files were found"
我使用4060324066583245 作为测试数据在rubular.com 上检查了正则表达式,该数据包含在我的测试文档中,Rubular 验证该数字是否与正则表达式匹配。总结一下:
- 爬虫使用
teststring处理第一个案例 - 验证爬虫是否正确扫描我的文件系统并读取所需文件类型的内容 - Rubular 验证我的正则表达式成功匹配我的测试信用卡号
4060324066583245 - 爬虫找不到测试信用卡号。
有什么建议吗?我不知道为什么 Rubular 将正则表达式显示为工作,但脚本在我的机器上运行时却无法工作。
【问题讨论】:
-
您使用的是什么操作系统? Mac OS 和 Linux 包括
grep,它可以轻松解决这个问题,并且比 Ruby 运行得更快。 -
我在 OS X 上,但我希望程序也能在 Windows 上运行。
标签: ruby regex macos filesystems web-crawler