Home > database >  Ruby multiple regex gsub in one pass, using different capture groups
Ruby multiple regex gsub in one pass, using different capture groups

Time:07-16

In Ruby, how do I do the following in one pass:

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

If text = "==aaa== =BBB=", return value should be "AAA bbb"

CodePudding user response:

You can use

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

See the Ruby demo and the regex demo.

Details:

  • (={1,2}) - one or two = chars captured into Group 1
  • (.*?) - Group 2: any zero or more chars other than line break chars as few as possible
  • \1 - the same text as captured in Group 1.

If Group 1 holds the = value, the replacement is the lowercased Group 2 value, else, it is the uppercased Group 2 value.

  • Related