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. 分裂字符串,但保持內部字符串完好?