简体   繁体   English

用正则表达式和捕获替换

[英]Replacement with regular expression and capture

The method below is supposed to transform "snake_case" to "CamelCase" . 以下方法应该将"snake_case"转换为"CamelCase"

def zebulansNightmare(string)
  string.gsub(/_(.)/){$1.upcase}
end

With string "camel_case" , I expect gsub(/_(.)/) to match c after the _ . 使用字符串"camel_case" ,我希望gsub(/_(.)/)_之后匹配c I understood that $1 is the first matched letter: the capital letter. 我知道$1是第一个匹配的字母:大写字母。 But it works like it's substituting _ with the capital letter. 但是它的工作方式就像用大写字母替换_一样。 Why has the _ disappeared? 为什么_消失了?

You are right that $1 is the captured value, however, the gsub matches the letter with _ before it, and the whole match gets replaced. 没错, $1是捕获的值,但是, gsub将字母与_匹配,然后替换了整个匹配项。 You need to reinsert _ to the result: 您需要将_重新插入结果:

"camel_case".gsub(/_(.)/){"_#{$1.upcase}"}

See the IDEONE demo IDEONE演示

BTW, if you only plan to match _ followed with a letter (so as not to waste time and resources on trying to turn non-letters to upper case), you can use the following regex: 顺便说一句,如果您只打算匹配_后跟一个字母 (以免浪费时间和资源来尝试将非字母转换为大写字母),则可以使用以下正则表达式:

/_(\p{Ll})/

Where \\p{Ll} is any lowercase Unicode letter. 其中\\p{Ll}是任何小写的Unicode字母。

def zebulans_nightmare(string)
  string.gsub(/\B_[a-z0-9]/) { |s| s[1].upcase }
end

zebulans_nightmare("case_of_snakes")
  #=> "caseOfSnakes" 
zebulans_nightmare("case_of_3_snakes")
  #=> "caseOf3Snakes" 
zebulans_nightmare("_case_of_3_snakes")
  #=> "_caseOf3Snakes" 

\\B matches non-word boundaries . \\B 匹配非单词边界

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM