[英]Splitting a string into words and punctuation with Ruby
我在Ruby工作,我想將一個字符串及其標點分割成一個數組,但我想將撇號和連字符視為單詞的一部分。 例如,
s = "here...is a happy-go-lucky string that I'm writing"
應該成為
["here", "...", "is", "a", "happy-go-lucky", "string", "that", "I'm", "writing"].
我得到的最接近的仍然是不充分的,因為它沒有正確地將連字符和撇號視為單詞的一部分。
這是我到目前為止最接近的:
s.scan(/\w+|\W+/).select {|x| x.match(/\S/)}
產量
["here", "...", "is", "a", "happy", "-", "go", "-", "lucky", "string", "that", "I", "'", "m", "writing"]
。
您可以嘗試以下方法:
s.scan(/[\w'-]+|[[:punct:]]+/)
#=> ["here", "...", "is", "a", "happy-go-lucky", "string", "that", "I'm", "writing"]
你很親密:
s.scan(/[\w'-]+|[.,!?]+/)
這個想法是我們匹配任何可能帶有'
/ -
單詞或標點字符。
在幾乎放棄然后修補一些之后,我似乎已經解決了這個難題。 這似乎有效: s.scan(/[\\w'-]+|\\W+/).select {|x| x.match(/\\S/)}
s.scan(/[\\w'-]+|\\W+/).select {|x| x.match(/\\S/)}
。 它產生["here", "...", "is", "a", "happy-go-lucky", "string", "that", "I'm", "writing"]
。
有沒有更#select
方法來做到這一點,而不必使用#select
?
使用split
方法。
例:
str = "word, anotherWord, foo"
puts str.split(",")
它回來了
word
anotherWord
foo
希望這對你有用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.