【发布时间】:2016-02-08 06:12:33
【问题描述】:
我需要从一个字符串中创建一个数组,并且我必须使用多个分隔符(除了空格):
! @ $ # % ^ & * ( ) - = _ + [ ] : ; , . / ? \ |
my_string.split(/[\s!@$#%^&*()-=_+[]:;,./<>?\|]/)
这是练习:
给定一个句子,返回一个包含所有其他单词的数组。 标点不是单词的一部分,除非它是一个收缩。 为了不必编写实际的语言解析器,不会有任何太复杂的标点符号。 不会有不属于收缩的“'”。
假设不考虑这些字符中的每一个:
! @ $ # % ^ & * ( ) - = _ + [ ] : ; , . / ? \ |
例子:
alternate_words("Lorem ipsum dolor sit amet.") # => ["Lorem", "dolor", "amet"]
alternate_words("Can't we all get along?") # => ["Can't", "all", "along"]
alternate_words("Elementary, my dear Watson!") # => ["Elementary", "dear"]
这就是我正在尝试的方式:
def every_other_word(sentence)
my_words = []
words = sentence.split(/[\s!@$^&*()-=_+[\]:;,.\/#%<>?\|]/)
words.each_with_index do |w, i|
next if i.odd?
my_words << w
end
my_words
end
这是我得到的错误:
$ ruby ./session2/3-challenge/7_array.rb
./session2/3-challenge/7_array.rb:14: premature end of char-class: /[\s!@$^&*()-=_+[\]:;,.\/#%<>?\|]/
【问题讨论】:
-
你需要用反斜杠转义
[、]、/(如果你也想要这个字符,最后是`\`,否则你不需要转义管道) .将连字符放在类的开头或结尾或将其转义,因为字符类中的连字符用于定义字符范围(参见 ascii 表)。 -
假设Ruby使用
/../范式定界符和quote like运算符,第一个正则表达式my_string.split(/[\s!@$#%^&*()-=_+[]:;,./<>?\|]/)有问题,类中的/没有转义(它兼作定界符) .除此之外,课程在[\s!@$#%^&*()-=_+[]words = sentence.split(/[\s!@$^&*()-=_+[\]:;,.\/#%<>?\|]/) 绝对没问题。 -
您还需要转义
-或将其放在末尾,否则您有一个范围。
标签: arrays ruby regex string split