按空格、句点、逗号或双引号拆分,而不是按单引号拆分:
str = %Q{this is the.string to's split,real "ok" nice-like.}
str.split(/\s|\.|,|"/)
=> ["this", "is", "the", "string", "", "", "", "to's", "split", "real", "", "ok", "", "nice-like"]
如何 Eloquent 地删除空字符串?
如何 Eloquent 地删除短于 MIN_LENGTH 的字符串?
最佳答案
在这种情况下使用split
的想法是不正确的。您应该使用 scan
。
str = %Q{this is the.string to's split,real "ok" nice-like.}
str.scan(/[\w'-]+/)
# => ["this", "is", "the", "string", "to's", "split", "real", "ok", "nice-like"]
为了匹配 MIN_LENGTH
或更长的字符串,请这样做:
MIN_LENGTH = 3
str.scan(/[\w'-]{#{MIN_LENGTH},}/)
# => ["this", "the", "string", "to's", "split", "real", "nice-like"]
什么时候用split,什么时候用scan
- 当分隔符很乱并且很难用正则表达式匹配它们时,请使用
scan
。 - 当要提取的子字符串很杂乱并且很难用正则表达式匹配它们时,使用
split
。 - 当您想对要提取的子字符串的形式施加条件时,您可以
扫描
。 - 如果您想对定界符的形式施加条件,请使用
split
。
关于ruby-on-rails - 如何在不创建空字符串的情况下在 Ruby 中拆分文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9713609/