我正在构建一个爬虫来搜索我的文件系统中包含特定信息的特定文档。然而,regex部分让我有点困惑。我的桌面上有一个包含'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"我将rubular.com上的regex作为测试数据(包含在我的测试文档中)检查了4060324066583245,Rubular验证了这个数字是否与regex匹配。总结一下:
teststring在第一种情况下工作--验证爬虫是否正确地扫描了我的文件系统并读取了所需文件类型的内容。4060324066583245匹配。有什么建议吗?我不明白为什么Rubular显示正则表达式工作,但是脚本在我的机器上运行时不能工作。
发布于 2012-12-18 18:25:02
^和$分别是将匹配绑定到字符串开始和结束的锚点。
因此,^[0-9]{4}$将与"1234"相匹配,而不匹配"12345"或" 1234 "等。
您应该使用单词边界,而不是:
if contents =~ /\b4[0-9]{12}(?:[0-9]{3})?\b/https://stackoverflow.com/questions/13939051
复制相似问题