【问题标题】:Split by multiple delimiters in Ruby在 Ruby 中被多个分隔符分割
【发布时间】:2016-02-08 06:12:33
【问题描述】:

我需要从一个字符串中创建一个数组,并且我必须使用多个分隔符(除了空格):

! @ $ # % ^ & * ( ) - = _ + [ ] : ; , . / ? \ |

我看了herehere,解决办法好像是用:

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!@$#%^&amp;*()-=_+[]:;,./&lt;&gt;?\|]/)有问题,类中的/没有转义(它兼作定界符) .除此之外,课程在[\s!@$#%^&amp;*()-=_+[]words = sentence.split(/[\s!@$^&*()-=_+[\]:;,.\/#%<>?\|]/) 绝对没问题。
  • 您还需要转义 - 或将其放在末尾,否则您有一个范围。

标签: arrays ruby regex string split


【解决方案1】:

大多数提到的定界字符在正则表达式文字中都有特殊含义。例如,] 不是] 字符而是the end of a character class。链接的页面应该列出所有这些并解释它们的含义。

这些字符需要在正则表达式文字中通过在每个字符前面加上\ 进行转义。在这个字符类中,-[]/\ 需要转义(^ 仅在它是第一个字符时才需要,- 仅在它不是最后一个不是的字符):

/[\s!@$#%^&*()\-=_+\[\]:;,.\/<>?\\|]/

您也可以让 Ruby 使用Regexp.escape(又名Regexp.quote)来完成这项工作。它会转义每个特殊字符,但生成的正则表达式将是等效的:

escaped_characters = Regexp.escape('!@$#%^&*()-=_+[]:;,./<>?\|')
/[\s#{escaped_characters}]/

顺便说一下,\s 不仅仅是双引号字符串文字中的空格(一个奇怪的功能),它也匹配其他 ASCII 空白字符(\n\t\r、@987654341 @ 和 \v)。

【讨论】:

    【解决方案2】:

    你被告知没有撇号,你可以忽略:

    BADDIES = '!@$#%^&*()-=_+[]:;,./?\|'

    为什么不呢:

    我们可以这样写:

    str = "Now it the time for all good Rubiests to come to the aid of their " +
          "fellow coders (except for Bob)! Is that not true?"
    
    str.delete(BADDIES).split.each_slice(2).map(&:first)
      #=> ["Now", "the", "for", "good", "to", "to", "aid", "their",
      #    "coders", "for", "Is", "not"] 
    

    看,妈!没有正则表达式!

    【讨论】:

    • OP 的问题听起来像是家庭作业,否则他为什么要在这个简单的“练习”中使用正则表达式。
    猜你喜欢
    • 1970-01-01
    • 2016-04-01
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 2021-09-25
    相关资源
    最近更新 更多