1
A
回答
2
您可以使用String.split和正则表达式模式作为参数。 像这样:
"Hello_World I am Learning,Ruby".split /[ _,.!?]/
=> ["Hello", "World", "I", "am", "Learning", "Ruby"]
1
ruby-1.9.2-p290 :022 > str = "Hello_World I am Learning,Ruby"
ruby-1.9.2-p290 :023 > str.split(/\s|,|_/)
=> ["Hello", "World", "I", "am", "Learning", "Ruby"]
0
虽然上面的例子中工作,我想将字符串分割的话拆就不会被认为是任何一种文字的一部分字符的时候它可能会更好。要做到这一点,我这样做:
str = "Hello_World I am Learning,Ruby"
str.split(/[^a-zA-Z]/).reject(&:empty?).compact
本声明如下:
- 拆分由不在字母字符的字符串
- 然后拒绝任何为空字符串
- ,并移除阵列
然后将处理的话大部分组合的所有空值。上面的例子要求你列出你想匹配的所有字符。指定不认为是单词的一部分的字符要容易得多。
1
String#Scan似乎是一个合适的方法完成这个任务
irb(main):018:0> "Hello_World I am Learning,Ruby".scan(/[a-z]+/i)
=> ["Hello", "World", "I", "am", "Learning", "Ruby"]
,或者您可以使用内置的匹配\w
irb(main):020:0> "Hello_World I am Learning,Ruby".scan(/\w+/)
=> ["Hello_World", "I", "am", "Learning", "Ruby"]
4
你可以使用\ W任何非单词字符:
"Hello_World I am Learning,Ruby".split /[\W_]/
=> ["Hello", "World", "I", "am", "Learning", "Ruby"]
"Hello_World I am Learning, Ruby".split /[\W_]+/
=> ["Hello", "World", "I", "am", "Learning", "Ruby"]
0
只是为了好玩,1.9的Unicode识别版本(或1.8与Oniguruma):
>> "This_µstring has words.and thing's".split(/[^\p{Word}']|\p{Connector_Punctuation}/)
=> ["This", "µstring", "has", "words", "and", "thing's"]
或许:
>> "This_µstring has words.and thing's".split(/[^\p{Word}']|_/)
=> ["This", "µstring", "has", "words", "and", "thing's"]
真正的问题是确定哪些字符序列构成在这种情况下一个 “字”。您可能想要查看Oniguruma docs以了解支持的字符属性,Wikipedia has some notes on the properties。
相关问题
- 1. 分裂基于多个字符的字符串定界符
- 2. Ruby:将字符串拆分为最多40个字符的子字符串
- 3. 分裂在VB字符串
- 4. 字符串分裂在JavaScript?
- 5. 分裂ArrayList的字符串
- 6. 分裂的JavaScript字符串
- 7. 分裂Java字符串
- 8. 与preg_split分裂字符串
- 9. Android-分裂URL字符串
- 10. 分裂根据字段分隔为每行一个字符串
- 11. 为什么字符串不分裂?
- 12. 字符串为十六进制分裂
- 13. 分裂出一个字符串
- 14. 分裂一个困难的字符串
- 15. C++分裂一个字符串
- 16. JAVA - 分裂字符串2定界符
- 17. 蟒蛇 - 拆分字符串列表分为多个字符串
- 18. 在Ruby中的字符串#分裂行为不预期
- 19. Python的分裂()返回多个字符
- 20. 将单个字符串分解为多个字符串C++?
- 21. 打破一个PHP字符串分为多个字符串
- 22. 分裂可变长度分隔为多行(SQL)字符串
- 23. 分隔字符串分隔符分裂成Scala中的每个字符
- 24. 劈裂字符串
- 25. VBA分裂小数点后的字符串由2个字符
- 26. 将字符串拆分为多个字符串(当某个字符发生时)
- 27. 分割字符串,请记住分裂
- 28. 分裂阵列分隔成字符串
- 29. 分裂空格分隔字符串
- 30. 分裂字符串,但保持内部字符串完好?