Rails中的简单正则表达式问题

时间:2010-12-18 07:05:12

标签: ruby-on-rails ruby regex

确定。已经晚了,我累了。

我想匹配字符串中的字符。具体来说,'a'的外观。和“一个半”一样。

如果我有一个全部小写的字符串。

"one and a half is always good" # what a dumb example. No idea how I thought of that.

我打电话给它标题化

"one and a half is always good".titleize #=> "One And A Half Is Always Good"

这是错误的,因为'And'和'A'应该是小写的。明显。

所以,我可以做到

"One and a Half Is always Good".titleize.tr('And', 'and') #=> "One and a Half Is always Good"

我的问题:如何将“A”变为“a”而不将“Always”变为“always”?

2 个答案:

答案 0 :(得分:2)

这样做:

require 'active_support/all'
str = "one and a half is always good" #=> "one and a half is always good"

str.titleize.gsub(%r{\b(A|And|Is)\b}i){ |w| w.downcase } #=> "One and a Half is Always Good"

str.titleize.gsub(%r{\b(A(nd)?|Is)\b}i){ |w| w.downcase } #=> "One and a Half is Always Good"

选择最后两行中的任何一行。正则表达式模式可以在别处创建并作为变量传入,以便维护或代码清洁。

答案 1 :(得分:2)

我喜欢Greg的双线(首先标题化,然后使用正则表达式来减少选定的单词。)FWIW,这是我在项目中使用的函数。经过良好测试,虽然更加冗长。你会注意到我在ActiveSupport中覆盖了标题:

class String
  #
  # A better titleize that creates a usable
  # title according to English grammar rules.
  #
  def titleize
    count  = 0
    result = []

    for w in self.downcase.split
      count += 1
      if count == 1
        # Always capitalize the first word.
        result << w.capitalize
      else
        unless ['a','an','and','by','for','in','is','of','not','on','or','over','the','to','under'].include? w
          result << w.capitalize
        else
          result << w
        end
      end
    end

    return result.join(' ')
  end
end