加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 01:31:50 所属栏目:百科 来源:网络整理
导读:使用 Ruby语言,我想将每个句子的第一个字母大写,并在每个句子结尾处的句号之前删除任何空格.别的什么都不应该改变. Input = "this is the First Sentence . this is the Second Sentence ." Output = "This is the First Sentence. This is the Second Sente
使用 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."

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

UPDATE

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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读