繁体   English   中英

使用Ruby将字符串拆分为单词和标点符号

[英]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

希望这对你有用!

你也可以这个http://ruby.about.com/od/advancedruby/a/split.htm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM