Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Ruby将字符串拆分为单词和标点符号 我在Ruby中工作,我想把一个字符串和它的标点分割成一个数组,但是我想把撇号和连字符当作单词的一部分。比如说, s = "here...is a happy-go-lucky string that I'm writing"_Ruby_Regex - Fatal编程技术网

使用Ruby将字符串拆分为单词和标点符号 我在Ruby中工作,我想把一个字符串和它的标点分割成一个数组,但是我想把撇号和连字符当作单词的一部分。比如说, s = "here...is a happy-go-lucky string that I'm writing"

使用Ruby将字符串拆分为单词和标点符号 我在Ruby中工作,我想把一个字符串和它的标点分割成一个数组,但是我想把撇号和连字符当作单词的一部分。比如说, s = "here...is a happy-go-lucky string that I'm writing",ruby,regex,Ruby,Regex,应该成为 ["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", "

应该成为

["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"]
.

使用拆分方法

例如:

str = "word, anotherWord, foo"
puts str.split(",")
它回来了

word
anotherWord
foo
希望它对你有用


你也可以检查这个

在几乎放弃之后,再修补一些,我似乎已经解决了这个难题。这似乎有效:s.scan/[\w'-]+|\w+/。选择{x | x.match/\s/}。它产生[这里,…,是,一个,乐天派,字符串,我在写]


有没有一种更干净的方法可以做到这一点,而不必使用select?

您可以尝试以下方法:

s.scan(/[\w'-]+|[[:punct:]]+/)
#=> ["here", "...", "is", "a", "happy-go-lucky", "string", "that", "I'm", "writing"]
你很接近:

s.scan(/[\w'-]+|[.,!?]+/)

我们的想法是,我们可以在单词中匹配可能带有“/”的单词或标点符号。

如果撇号是单词的一部分,为什么不在这里…是一个完整的单词?这里和是语义上独立的单词,尽管我正在分析的文本有时会涉及不好的标点符号习惯,但我正在分析一些Yelp评论^ ^。哇,你能参考一下你从哪里得到的:putt:东西吗?你可以参考POSIX类