SoFunction
Updated on 2025-04-09

Introduction to Ruby


5. Reverse reference of regular expressions

Like Perl, Ruby's natural support for regular expressions is their advantage. Friends who know Perl can see that Ruby's regular expressions are exactly the same as Perl in many places.

Backreference refers to a pattern enclosed in parentheses in a regular expression. The pattern on the following two lines is the same, but the second sentence adopts the form of backreference.
pat1 = /([\d\w])-([\d\w])/ pat2 = /([\d\w])-\1/
It should be noted that the brackets for the backreference must be located to the left of the reference position. In addition, if you want to match a number immediately after the backreference, you must enclose the backreference expression.
pat1 = /([\d\w])-(\1)0/ pat2 = /([\d\w])-\10/ # 0 print pat1 =~ "1-10" # nil print pat2 =~ "1-10"