Ruby - 将段落中每个句子的首字母大写

时间:2014-01-16 06:20:14

标签: ruby string

使用Ruby语言,我想将每个句子的第一个字母大写,并在每个句子结尾处的句号之前删除任何空格。别的什么都不应该改变。

Input =  "this is the First Sentence . this is the Second Sentence ."    
Output =  "This is the First Sentence. This is the Second Sentence."

谢谢大家。

2 个答案:

答案 0 :(得分:6)

使用正则表达式(String#gsub):

Input =  "this is the First Sentence . this is the Second Sentence ."    
Input.gsub(/[a-z][^.?!]*/) { |match| match[0].upcase + match[1..-1].rstrip }
# => "This is the First Sentence. This is the Second Sentence."

Input.gsub(/([a-z])([^.?!]*)/) { $1.upcase + $2.rstrip }  # Using capturing group
# => "This is the First Sentence. This is the Second Sentence."

我认为句子以.?!结尾。

<强>更新

input = "TESTest me is agreat. testme 5 is awesome"
input.gsub(/([a-z])((?:[^.?!]|\.(?=[a-z]))*)/i) { $1.upcase + $2.rstrip }
# => "TESTest me is agreat. Testme 5 is awesome"

input = "I'm headed to stackoverflow.com"
input.gsub(/([a-z])((?:[^.?!]|\.(?=[a-z]))*)/i) { $1.upcase + $2.rstrip }
# => "I'm headed to stackoverflow.com"

答案 1 :(得分:1)

Input.split('.').map(&:strip).map { |s|
  s[0].upcase + s[1..-1] + '.'
}.join(' ')
=> "This is the First Sentence. This is the Second Sentence."

我的第二种方法是更清洁但产生略有不同的输出:

Input.split('.').map(&:strip).map(&:capitalize).join('. ') + '.'
=> "This is the first sentence. This is the second sentence."

我不确定你是不是很好。