Mike Dalessio(Nokogiri核心开发人员的一半)给了我答案#nokogiri
(irc.freenode.net).看起来Nokogiri CSS和XPath搜索都不支持正则表达式匹配.这是他如何使用Nokogiri搜索正则表达式的解决方案:
require 'rubygems' require 'nokogiri' value = Nokogiri::HTML.parse(<<-HTML_END) "A
B
Bla
C
D
3
" HTML_END # my_block is given my_bl = "1" # my_eq corresponds to this regex my_eq = "[0-9]+" # full regex to search for in node ids full_regex = %r(eq-#{my_eq}_bl-#{my_bl}) filter_by_id = Class.new do attr_accessor :matches def initialize(regex) @regex = regex @matches = [] end def filter(node_set) @matches += node_set.find_all { |x| x['id'] =~ @regex } end end.new(full_regex) value.css("div.foo:filter()", filter_by_id) filter_by_id.matches.each do |node| puts node end3