[英]Ruby string split on more than one character
我有一個字符串,說“我正在學習的Hello_World,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文檔中所支持的字符屬性, Wikipedia也對該屬性進行了一些注釋 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.