【问题标题】:gem countries use Regexp宝石国家使用正则表达式
【发布时间】:2013-02-11 20:35:56
【问题描述】:

我使用的是 hexorx 的 country gem,这里是 gem 的链接
Countries gem

我在代码 country.rb 中看到,将 Regexp 作为搜索国家/地区的参数是可能的。问题是,我什至不知道如何使用正则表达式。
例如,我想做的是给我所有以“T”开头的国家。我试试这个

1.9.3-p327 :013 > c = Country.find_all_countries_by_name("/(T*)/")
 => []  

你怎么看,根本不起作用。

【问题讨论】:

    标签: regex ruby-on-rails-3 country


    【解决方案1】:

    所有以 T 开头的国家都类似于:

    c = Country.find_all_countries_by_name("/^T[A-Za-z ]*/")
    

    在这种情况下,您正在执行以下操作:

    / - start of the match
    ^ - matches the start of the string (so the next character MUST be first)
    T - literal T 
    [A-Za-z ] - a "character class" allowing any a-z upper or lower plus space
    * - repeat previous character (or character class) 0-many times
    

    这是学习正则表达式的绝佳资源:http://www.regular-expressions.info/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-14
      • 2019-04-22
      • 2011-10-06
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多