ruby regex replace capture group

To replace a capture group in a string using regular expressions in Ruby, you can use the gsub method. Here is an example with step-by-step explanations:

str = "Hello, my name is John Doe."
pattern = /(John) (Doe)/
replacement = "\\2, \\1"

new_str = str.gsub(pattern, replacement)
  1. Define the input string str that contains the text you want to modify.
  2. Define the regular expression pattern pattern using parentheses to capture the desired groups. In this example, we capture the first name "John" and the last name "Doe".
  3. Define the replacement string replacement using backreferences to the captured groups. In this example, we use \\2 to refer to the second captured group (last name) and \\1 to refer to the first captured group (first name). The order of the backreferences corresponds to the order of the captured groups in the pattern.
  4. Use the gsub method on the input string str with the pattern and replacement as arguments. This method replaces all occurrences of the pattern in the string with the replacement string.
  5. The modified string is stored in the new_str variable.

After executing the code, the value of new_str will be "Hello, my name is Doe, John.". The capture group "John Doe" is replaced with "Doe, John" using the backreferences in the replacement string.