Ruby 字符串拆分为单词而忽略所有特殊字符:更简单的查询 [英] Ruby string split into words ignoring all special characters: Simpler query

查看:39
本文介绍了Ruby 字符串拆分为单词而忽略所有特殊字符:更简单的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在使用非单词字符的任何地方将查询拆分为单词.例如:

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 and @do$$nice&acti*vities+enjoy good ?times."

应该输出:

["I", "am", "a", "great", "", "boy", "s", "and", "I", "like", "", "to", "have", "", "a", "lot", "of", "fun", "and", "", "do", "", "nice", "acti", "vities", "enjoy", "good", "", "times"] 

这行得通,但有没有更简单的方法?

This does the trick but is there a simpler way?

query.split(/[ ,'!:\\@\\$\\&\\*+?.-]/)

推荐答案

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.

这篇关于Ruby 字符串拆分为单词而忽略所有特殊字符:更简单的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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