我有这样的字符串:
THiS is a Li?ne of text
!THiS is a Line of text
((THiS is a Line of text.X
THiS is a Line of text
我想将每一行大写,但保持其原始形式。
到目前为止,我有:
puts the_string.gsub(/(^\W*?)([a-z])/) { |x| "#{$2.capitalize}"}
但这摆脱了空白。
你没有处理这个词的其余部分:
lines = [
" THiS is a Li?ne of text",
"!THiS is a Line of text",
"((THiS is a Line of text.X",
"THiS is a Line of text"
]
lines.each do |line|
puts line.gsub(/(\w+)/) { $1.capitalize }
end
# => This Is A Li?Ne Of Text
# => !This Is A Line Of Text
# => ((This Is A Line Of Text.X
# => This Is A Line Of Text
不确定您到底要达到什么目标,但这可能会有所帮助:
puts the_string.gsub(/(^\W*?)([a-z])/) { |x| "#{$1}#{$2.capitalize}"}
这也将第一个捕获的组(即空格)放回结果字符串中。
string = <<_
THiS is a Li?ne of text
!THiS is a Line of text
((THiS is a Line of text.X
THiS is a Line of text
_
string.gsub(/\w.*/, &:capitalize)
# =>
# This is a li?ne of text
# !This is a line of text
#((This is a line of text.x
# This is a line of text