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

标签 ruby regex

我目前正在为 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

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

最佳答案

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

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

关于ruby - 包含撇号的 Ruby 正则表达式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20525409/

相关文章:

ruby - 了解类方法的 method_added

ruby-on-rails - 用于读写 excel 和 csv 文件的 rails gem 或插件

ruby - 使用 Ruby,我如何迭代一个 for 循环 n.times

android - 在 Android 上以正确的格式输入 MAC 地址

java - 如何在Java中使用RegEx?

ruby-on-rails - Rails 4 – 如何从 NoMethodError 中解救并继续尝试方法?

ruby-on-rails - 当比例部分更改时,Rails 十进制(货币)数字不保存

php - MySQL PDO : Using bound placeholder within a regular expression

php - 删除包含开始 php 标记和空行的文件

带有端口验证的 URL 的正则表达式