如果该行的第一个单词(一个或多个)都在 CAPs 中,我想用大写单词替换这些单词(使用 ruby's .capitalize
)。例如“FOO BAR”到“Foo Bar”
我尝试了以下方法:
line.gsub!(/^([A-Z ]+)/, '\1'.capitalize)
和
line.gsub!(/^([A-Z ]+)/, "\\1".capitalize)
两者都不起作用。有没有办法做到这一点?
尝试:
line.gsub!(/^([A-Z ]+)/) { |w| w.capitalize }
在 IRB 中:
require 'active_support'
'FOO bar'.gsub(/^[A-Z]+/) { |w| w.capitalize }
=> "Foo bar"
或OP的版本:
'FOO bar'.gsub!(/^([A-Z ]+)/) { |w| w.capitalize }
=> "Foo bar"
对于前两个词,这是快速而肮脏的:
'FOO BAR'.gsub!(/^([A-Z ]+ [A-Z]+)/) { |w| w.capitalize }
=> "Foo bar"
您可以使用以下方法变得更漂亮:
'FOO BAR'.gsub!(/^((?<word>[A-Z]+) \g<word>)/) { |w| w.capitalize }
=> "Foo bar"
当然,在固定字符串上使用 的!
版本gsub
不会做任何有用的事情。
OP 添加了额外的约束:
require 'active_support'
line = 'AFOO BFOO CFOO DFOO e f g'
words = line[/^(?:[A-Z]+ )+/].split.map{ |w| w.capitalize } # => ["Afoo", "Bfoo", "Cfoo", "Dfoo"]
[words,line.split[words.size..-1]].join(' ') # => "Afoo Bfoo Cfoo Dfoo e f g"
You want to capitalize all words in line, correct? Try String#scan instead:
line.scan(/\w+|\W+/).map(&:capitalize).join
I'm no Ruby programmer, but I can see that you're calling capitalize
on the string \1
, which of course is just \1
again. You will want to look for something similar to PHP's preg_replace_callback
that will allow you to run regex matches through a function - in this case, capitalize
.