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