假设我有一个字符串:“hEY”
我想把它转换成“嘿”
string.gsub!(/([a-z])([A-Z]+ )/, '\1'.upcase)
这是我的想法,但是当我在 gsub 方法中使用它时,upcase 方法似乎什么都不做。这是为什么?
编辑:我想出了这个方法:
string.gsub!(/([a-z])([A-Z]+ )/) { |str| str.downcase!.capitalize! }
有没有办法在正则表达式中做到这一点?我不太明白 '\1' '\2' 的意思。那是反向引用吗?这是如何工作的
最佳答案
@sawa 有简单的答案,你已经用另一种机制编辑了你的问题。但是,要回答您的两个问题:
Is there a way to do this within the regex though?
不,Ruby 的正则表达式不支持大小写更改功能,如 some other regex flavors do .您可以通过查看 1.9 和 2.0 的官方 Ruby regex 文档并搜索“case”一词来向自己“证明”这一点:
- https://github.com/ruby/ruby/blob/ruby_1_9_3/doc/re.rdoc
- https://github.com/ruby/ruby/blob/ruby_2_0_0/doc/re.rdoc
I don't really understand the '\1' '\2' thing. Is that backreferencing? How does that work?
您对 \1
的使用是一种反向引用。当您使用 \1
时可以是反向引用等等在搜索模式中。例如,正则表达式 /f(.)\1/
会找到字母 f
, 后跟任何字符,后跟相同的字符(例如“foo”或“f!!”)。
在这种情况下,在传递给类似 String#gsub
的方法的替换字符串中,反向引用确实引用了先前的捕获。来自文档:
"If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern’s capture groups of the form
\d
, whered
is a group number, or\k<n>
, wheren
is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash."
在实践中,这意味着:
"hello world".gsub( /([aeiou])/, '_\1_' ) #=> "h_e_ll_o_ w_o_rld"
"hello world".gsub( /([aeiou])/, "_\1_" ) #=> "h_\u0001_ll_\u0001_ w_\u0001_rld"
"hello world".gsub( /([aeiou])/, "_\\1_" ) #=> "h_e_ll_o_ w_o_rld"
现在,您必须了解代码何时运行。在你的原始代码中......
string.gsub!(/([a-z])([A-Z]+ )/, '\1'.upcase)
...你正在做的是调用upcase
在字符串 '\1'
上(没有效果)然后然后调用gsub!
方法,传入一个正则表达式和一个字符串作为参数。
最后,另一种实现相同目标的方法是使用 block 形式,如下所示:
# Take your pick of which you prefer:
string.gsub!(/([a-z])([A-Z]+ )/){ $1.upcase << $2.downcase }
string.gsub!(/([a-z])([A-Z]+ )/){ [$1.upcase,$2.downcase].join }
string.gsub!(/([a-z])([A-Z]+ )/){ "#{$1.upcase}#{$2.downcase}" }
在 gsub 的 block 形式中,捕获的模式被设置为全局变量 $1
, $2
等,您可以使用它们来构造替换字符串。
关于ruby - 如何在 Ruby 中使用 RegEx 更改字符串中字母的大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15627434/