包含撇号的 Ruby 正则表达式是什么? [英] What is the Ruby regex for including apostrophes?

查看:37
本文介绍了包含撇号的 Ruby 正则表达式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在为 Ruby 做一个 exercism.io 并且无法通过最后的测试.最后的测试内容为:

I'm currently doing an exercism.io for Ruby and can't pass the last test. The last test reads :

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

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

What is the Regex for including the apostrophe?

推荐答案

您想使用字符类",如 http://www.regular-expressions.info/charclass.html.

You want to use a "character class", as described in http://www.regular-expressions.info/charclass.html.

因此,您可以使用 [\w']+ 代替 \w+,这表示您需要一个或多个 either一个单词字符或一个撇号.

So, instead of \w+, you can use [\w']+, which says you want one or more of either a word character or an apostrophe.

这篇关于包含撇号的 Ruby 正则表达式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆