0

if regex /([ab])([ax])\1x\1/ is run on the string aaxaxa what is the resulting value of $1 and $2.

Can some one explain in detailed in perl context.

I have tried with below perl script; Got an answer. But I would like to understand what does that regex is doing and how the answer came.

#! /usr/bin/perl

use strict;
use warnings;

my $str = "aaxaxa";

my($str1,$str2) = ($str =~ m/([ab])([ax])\1x\1/);

print "Substring-1: $str1 Substring-2: $str2 \n";

Output : Substring-1: a Substring-2: x

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • `([ab])([ax])\1x\1` regex should match `axaxa`, hence `\1` is `a` and `\2` is `x` – Avinash Raj Jan 20 '16 at 12:19
  • See [regex demo](https://regex101.com/r/hK9yI3/1). It explains everything, I think. Finds `a`, puts into Group 1, finds `x`, puts into Group 2, then matches the value in Group 1 (=`a`), then finds `x`, then again the value in Group 1. The keywords are *capturing group*, *backreferences* and *character class*. – Wiktor Stribiżew Jan 20 '16 at 12:20
  • The first `x` in `aaxaxa` can never match the literal x in your regex `/([ab])([ax])\1x\1/`, because the regex is looking to match 3 charcaters in front of it, but the string only has 2. So think of it as the literal `x` in your match expression matching the second `x` in `aaxaxa`, and the three characters before that matching the the regex `[ab][ax]\1` (with \1 being 'a') – beasy Jan 20 '16 at 13:04
  • Many Thanks Wiktor Stribiżew; This is really beautiful and very clear descriptive. – Venkata Naga Amar Boggavarapu Jan 20 '16 at 13:07

0 Answers0