Ruby string split into words ignoring all special characters: Simpler query

前端 未结 2 1258
滥情空心
滥情空心 2021-01-16 08:46

I need a query to be split into words everywhere a non word character is used. For example:

query = \"I am a great, boy\'s and I like! to have: a lot-of-fun         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-16 09:25

    query.split(/\W+/)
    # => ["I", "am", "a", "great", "boy", "s", "and", "I", "like", "to", "have", "a", "lot", "of", "fun", "and", "do", "nice", "acti", "vities", "enjoy", "good", "times"]
    
    query.scan(/\w+/)
    # => ["I", "am", "a", "great", "boy", "s", "and", "I", "like", "to", "have", "a", "lot", "of", "fun", "and", "do", "nice", "acti", "vities", "enjoy", "good", "times"]
    

    This is different from the expected output in that it does not include empty strings.

提交回复
热议问题