【问题标题】:Separating vowels and consonants区分元音和辅音
【发布时间】:2013-08-22 17:31:24
【问题描述】:

如何将元音和辅音从字符串中分离出来,以创建过滤器?

如何用其他字母代替辅音和元音

我想出了这个

(\A[^aeio]{1,3})(\w*)/

在网上搜索时,但不确定它是如何通过^aeio 的过滤部分来获取辅音的。

【问题讨论】:

    标签: ruby regex


    【解决方案1】:

    String.tr 适合转换文本:

    str = "while searching online, but not sure exactly how it works past the filtering part of ^aeio, to get consonants."
    p str.tr('aeiou', '')
    #=> "whl srchng nln, bt nt sr xctly hw t wrks pst th fltrng prt f ^, t gt cnsnnts."
    p str.tr('^aeiou', '') # the ^ negates
    #=>"ieeaioieuoueeaoioaeieiaoaeiooeooa"
    p str.tr('aeiou', 'eioua')
    #=>"wholi sierchong unloni, bat nut sari ixectly huw ot wurks pest thi foltirong pert uf ^eiou, tu git cunsunents."
    

    【讨论】:

      【解决方案2】:

      你的意思是这样拆分吗?

      1.9.3-p327 > s = "abcqwertyaeiouvbnmi"
       => "abcqwertyaeiouvbnmi"
      1.9.3-p327 > s.split(/([aeiou]+)/)
       => ["", "a", "bcqw", "e", "rty", "aeiou", "vbnm", "i"]
      

      如果是这样,那么您可以在生成的数组中循环替换字符。

      【讨论】:

        【解决方案3】:
        s = "iamagoodboy"
        v,c = s.chars.partition{|i| ["a","e","i","o","u"].include?(i)}
        p v #=> ["i", "a", "a", "o", "o", "o"]
        p c #=> ["m", "g", "d", "b", "y"]
        

        现在您可以随意迭代v 和c。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-02
          • 2018-05-23
          • 2015-12-17
          • 2020-10-30
          相关资源
          最近更新 更多