Ruby -- 将段落中每个句子的第一个字母大写 [英] Ruby -- capitalize first letter of every sentence in a paragraph

查看:44
本文介绍了Ruby -- 将段落中每个句子的第一个字母大写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using Ruby language, I would like to capitalize the first letter of every sentence, and also get rid of any space before the period at the end of every sentence. Nothing else should change.

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

谢谢各位.

推荐答案

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

Using regular expression (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 以 .?! 结尾.

I assumed the setence ends with ., ?, !.

更新

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 -- 将段落中每个句子的第一个字母大写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆