gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:48:04 28 4
gpt4 key购买 nike

使用 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."

我假设该句子以 .?! 结尾。

更新

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com