Ruby正则表达式标点符号

时间:2014-01-29 02:15:12

标签: ruby-on-rails ruby regex

我在写这篇文章时遇到了麻烦,以便将句子作为一个参数并对每个单词进行翻译而不会影响标点符号。

我还想继续使用分区方法。

如果我可以将报价保持在一起会很好,例如:

“我说过这个”,我说。

将是:

“我aidsay histay”,我说。

def convert_sentence_pig_latin(sentence)
  p split_sentence = sentence.split(/\W/)
  pig_latin_sentence = []
  split_sentence.each do |word|
    if word.match(/^[^aeiou]+/x)
      pig_latin_sentence << word.partition(/^[^aeiou]+/x)[2] +  word.partition(/^[^aeiou]+/x)[1] + "ay"
    else
      pig_latin_sentence << word
    end
  end
  rejoined_pig_sentence = pig_latin_sentence.join(" ").downcase + "."
  p rejoined_pig_sentence.capitalize
end

convert_sentence_pig_latin("Mary had a little lamb.")

2 个答案:

答案 0 :(得分:1)

您的主要问题是[^aeiou]匹配该范围之外的每个字符,包括空格,逗号,引号等。

如果我是你,我会使用辅音的正面匹配,即。 [b-df-hj-np-tv-z]我也会把那个正则表达式放在一个变量中,所以你不必重复三次。

另外,如果你感兴趣的话,有办法让你的convert_sentence_pig_latin方法成为一个单一的gsub,它会在一遍中完成整个句子。

更新

...因为你问过......

sentence.gsub( /\b([b-df-hj-np-tv-z])(\w+)/i ) { "#{$2}#{$1}ay" }

答案 1 :(得分:0)

# iterate over and replace regexp matches using gsub
def convert_sentence_pig_latin2(sentence)
  r = /^[^aeiou]+/i
  sentence.gsub(/"([^"]*)"/m) {|x| x.gsub(/\w+/) {|y| y =~ r ? "#{y.partition(r)[2]}#{y.partition(r)[1]}ay" : y}}
end
puts convert_sentence_pig_latin2('"I said this", I said.')

# define instance method: String#to_pl
class String
  R = Regexp.new '^[^aeiou]+', true # => /^[^aeiou]+/i
  def to_pl
    self.gsub(/"([^"]*)"/m) {|x| x.gsub(/\w+/) {|y| y =~ R ? "#{y.partition(R)[2]}#{y.partition(R)[1]}ay" : y}}
  end
end
puts '"I said this", I said.'.to_pl

来源:

http://www.ruby-doc.org/core-2.1.0/Regexp.html

http://ruby-doc.org/core-2.0/String.html#method-i-gsub