I was wondering whether I could use a part of the match within the match expression.
I would need that for automatic program testing, where some random pattern is occurring twice in the output, like this:
kfvggfhuvgdnjhrk=kfvggfhuvgdnjhrk
So the first attempt was using (for expect
):
-re "\r\n\[cbdefghijklnrtuv\]{16}=\[cbdefghijklnrtuv\]{16}\r\n"
This works; however the strings left and right of =
may be different.
In Perl 5.26.1 I was playing with the debugger, I I found out this (with a simplified example):
main::(-e:1): 1
DB<1> x 'a=a' =~ /^(a)=$1$/
empty array
DB<2> x 'a=a' =~ /^(a)=\g1$/
0 'a'
DB<3> x 'ab=ab' =~ /^(ab)=\g1$/
0 'ab'
DB<4> x 'ab=ab' =~ /^(ab)=\g1b$/
empty array
DB<5> q
So for some reason $1
does not work, but \g1
does!
Now I wonder if something similar exists for expect regular expressions.
If I understood correctly, if you want to match the same text as already captured text, you need to:
\1
to reference first capturing group, \2
for second, and so on, in our case \1
will be enough.So the pattern to use is
^([^=]+)=\1$
Explanation:
^
- assert start of text
(...)
- capturing group
[^=]+
- match one or more characters other than =
=
- match =
literally
\1
- match the same text as in first capturing group
$
- assert end of text