【问题标题】:What is the Ruby regex for including apostrophes?包含撇号的 Ruby 正则表达式是什么?
【发布时间】:2013-12-29 19:06:34
【问题描述】:

我目前正在为 Ruby 做一个 exercism.io,但无法通过最后一次测试。最后的测试显示:

def test_with_apostrophes
  phrase = Phrase.new("First: don't laugh. Then: don't cry.")
  counts = {"first"=>1, "don't"=>2, "laugh"=>1, "then"=>1, "cry"=>1}
  assert_equal counts, phrase.word_count
end

我收到的错误是:

1) Failure:
 PhraseTest#test_with_apostrophes [word_count_test.rb:61]:
 --- expected
 +++ actual
 @@ -1 +1 @@
 -{"first"=>1, "don't"=>2, "laugh"=>1, "then"=>1, "cry"=>1}
 +{"first"=>1, "don"=>2, "t"=>2, "laugh"=>1, "then"=>1, "cry"=>1}

我当前的代码是:

class Phrase
  attr_reader :input

  def initialize(input)
    @input = input
  end

  def word_count
    count = {}
    splitted = input.downcase.scan(/\w+/)
    splitted.each do | word |
    if !count.key?(word)
     count[word] = 1
    else
     count[word] = count[word] + 1
    end
  end
  count
 end
end

包含撇号的正则表达式是什么?

【问题讨论】:

    标签: ruby regex


    【解决方案1】:

    您想使用“字符类”,如http://www.regular-expressions.info/charclass.html 中所述。

    因此,您可以使用[\w']+ 而不是\w+,它表示您想要一个或多个任一单词字符或撇号。

    【讨论】:

    • 根据您的反馈更新了问题。谢谢。
    • 这行得通:splitted = input.downcase.scan(/[\w']+/)
    • 对,这就是我的建议,以 w 大写拼写错误为模。 :-)
    【解决方案2】:

    试试:

    splitted = input.downcase.scan(/[\w-']+/)
    

    【讨论】:

      【解决方案3】:

      试试这个来获取你的词频,

      words_freq = Hash.new(0)
      
      "First: don't laugh. Then: don't cry.".split(/\s+/).each { |word| words_freq[word.downcase.delete(':|.')] += 1 }
      

      #words_freq = {"first"=>1, "don't"=>2, "laugh"=>1, "then"=>1, "cry"=>1}

      【讨论】:

      • 这不会通过有几个原因。首先,冒号在匹配的单词中。其次,words_freq 中的键有大写字母。
      【解决方案4】:

      我已经尝试了上述所有解决方案,但在针对“首先:不要笑。然后:不要哭。”测试正则表达式时,它们都不适合我。

      我改用了splitted = input.downcase.scan(/\w+\'*\w|\w/)

      您还可以重构您的 word_acount 方法以使用 each_with_object,如下所示:

      ["don't","do","don't","try"].each_with_object(Hash.new(0)) do |item, hash|
        hash[item] += 1
      end
      => { "don't" => 2, "do" => 1, "try" => 1 }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-12
        • 2015-04-22
        • 2022-01-06
        相关资源
        最近更新 更多