使用Ruby语言,我想把每个句子的第一个字母大写,同时去掉每个句子末尾句号之前的任何空格。其他什么都不应该改变。

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

谢谢各位。

最佳答案

使用正则表达式( 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."

我假设 setence 以 .?! 结尾。

更新
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"

关于Ruby -- 将段落中每个句子的第一个字母大写,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21154625/

10-11 22:29
查看更多