简体   繁体   English

Ruby 多个正则表达式 gsub 一次通过,使用不同的捕获组

[英]Ruby multiple regex gsub in one pass, using different capture groups

In Ruby, how do I do the following in one pass:在 Ruby 中,如何一次性完成以下操作:

text.gsub(/==(.+?)==/){$1.upcase}.gsub(/=(.+?)=/){$1.downcase}

If text = "==aaa== =BBB=" , return value should be "AAA bbb"如果text = "==aaa== =BBB=" ,返回值应该是"AAA bbb"

You can use您可以使用

text.gsub(/(={1,2})(.*?)\1/) { $1.length == 1 ? $2.downcase : $2.upcase}

See the Ruby demo and the regex demo .请参阅Ruby 演示正则表达式演示

Details :详情

  • (={1,2}) - one or two = chars captured into Group 1 (={1,2}) - 一个或两个=捕获到第 1 组的字符
  • (.*?) - Group 2: any zero or more chars other than line break chars as few as possible (.*?) - 第 2 组:除换行符之外的任何零个或多个字符尽可能少
  • \1 - the same text as captured in Group 1. \1 - 与第 1 组中捕获的文本相同。

If Group 1 holds the = value, the replacement is the lowercased Group 2 value, else, it is the uppercased Group 2 value.如果 Group 1 持有=值,则替换为小写的 Group 2 值,否则为大写的 Group 2 值。

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

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