What is the Ruby regex for including apostrophes?

前端 未结 3 1741
醉话见心
醉话见心 2021-01-24 22:01

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\'         


        
相关标签:
3条回答
  • 2021-01-24 22:18

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

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

    0 讨论(0)
  • 2021-01-24 22:28

    Try this for getting your frequency of words,

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

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

    0 讨论(0)
  • Try:

    splitted = input.downcase.scan(/[\w-']+/)
    
    0 讨论(0)
提交回复
热议问题