【发布时间】:2011-10-11 09:46:43
【问题描述】:
我有一个字符串,说“Hello_World I am Learning,Ruby”。 我想将此字符串拆分为每个不同的单词,最好的方法是什么?
谢谢! C.
【问题讨论】:
我有一个字符串,说“Hello_World I am Learning,Ruby”。 我想将此字符串拆分为每个不同的单词,最好的方法是什么?
谢谢! C.
【问题讨论】:
您可以将 \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"]
【讨论】:
您可以使用带有正则表达式模式的 String.split 作为参数。 像这样:
"Hello_World I am Learning,Ruby".split /[ _,.!?]/
=> ["Hello", "World", "I", "am", "Learning", "Ruby"]
【讨论】:
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"]
【讨论】:
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"]
【讨论】:
虽然上述示例有效,但我认为将字符串拆分为单词以拆分不被视为任何单词一部分的字符可能会更好。为此,我这样做了:
str = "Hello_World I am Learning,Ruby"
str.split(/[^a-zA-Z]/).reject(&:empty?).compact
此语句执行以下操作:
然后它将处理大多数单词组合。上面的示例要求您列出要匹配的所有字符。指定您不会认为是单词一部分的字符要容易得多。
【讨论】:
只是为了好玩,一个支持 Unicode 的 1.9 版本(或带有 Oniguruma 的 1.8):
>> "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 也是如此。
【讨论】: