如何创建不区分大小写的 nokogiri Xpath 选择器? [英] How can I create a nokogiri case insensitive Xpath selector?

查看:60
本文介绍了如何创建不区分大小写的 nokogiri Xpath 选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 nokogiri 选择关键字"属性,如下所示:

puts page.parser.xpath("//meta[@name='keywords']").to_html

我使用的其中一个页面的关键字标签带有大写的K",这促使我使查询不区分大小写.

AND <meta name="关键字">

所以,我的问题是:使 nokogiri 选择不区分大小写的最佳方法是什么?

编辑 Tomalak 下面的建议非常适合这个特定问题.我也想用这个例子来帮助更好地理解 nokogiri 并且有几个我想知道但没有成功搜索的问题.例如,正则表达式伪类"Nokogiri Docs 是否适用于此类问题?>

我也对 nokogiri 中的matches?() 方法很好奇.我无法找到有关该方法的任何说明.它与 XPath 2.0 中的匹配"概念有什么关系(因此它可以用来解决这个问题)?

非常感谢.

解决方案

为了易读性而包装:

放入 page.parser.xpath("//元[翻译(@名称,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz') = '关键字']").to_html

XPath 1.0 中没有小写"功能,因此您必须使用 translate() 来处理这种事情.根据需要添加重音字母.

I'm using nokogiri to select the 'keywords' attribute like this:

puts page.parser.xpath("//meta[@name='keywords']").to_html

One of the pages I'm working with has the keywords label with a capital "K" which has motivated me to make the query case insensitive.

<meta name="keywords"> AND <meta name="Keywords"> 

So, my question is: What is the best way to make a nokogiri selection case insensitive?

EDIT Tomalak's suggestion below works great for this specific problem. I'd like to also use this example to help understand nokogiri better though and have a couple issues that I'm wondering about and have not been successful searching for. For example, are the regex 'pseudo classes' Nokogiri Docs appropriate for a problem like this?

I'm also curious about the matches?() method in nokogiri. I have not been able to find any clarification on the method. Does it have anything to do with the 'matches' concept in XPath 2.0 (and therefore could it be used to solve this problem)?

Thanks very much.

解决方案

Wrapped for legibility:

puts page.parser.xpath("
  //meta[
    translate(
      @name, 
      'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 
      'abcdefghijklmnopqrstuvwxyz'
    ) = 'keywords'
  ]
").to_html

There is no "to lower case" function in XPath 1.0, so you have to use translate() for this kind of thing. Add accented letters as necessary.

这篇关于如何创建不区分大小写的 nokogiri Xpath 选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆