把每句话的首字母大写。

时间:2022-08-11 16:51:58

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.

使用Ruby语言,我想把每句话的第一个字母大写,并且在每句话结尾的句点之前去掉任何空格。应该改变。

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

Thank you folks.

谢谢你们。

2 个解决方案

#1


5  

Using regular expression (String#gsub):

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

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

我以为结局是……

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

#2


1  

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

My second approach is cleaner but produces a slightly different output:

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

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

I'm not sure if you're fine with it.

我不确定你对它是否满意。

#1


5  

Using regular expression (String#gsub):

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

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

我以为结局是……

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

#2


1  

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

My second approach is cleaner but produces a slightly different output:

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

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

I'm not sure if you're fine with it.

我不确定你对它是否满意。

相关文章