What do $0 $1 $2 do in replace?

For the Compleat Fan
Locked
cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

What do $0 $1 $2 do in replace?

Post by cormullion »

replace with regular expressions also sets the internal variables $0 $1 $2 ... etc. with the contents of the expressions and sub-expressions found.
That's what the manual says. But what do $0 $1 etc really get set to? $0 is the entire matched pattern? Does it depend on whether you use parentheses in the regex pattern?

Lutz
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

Yes, $0 is for the whole pattern and $1, $2 etc. for the subpatterns indicated by (,) parens. Here is a quick example:

Code: Select all

> (find {(http://)(new.*\.)(org):(\d\d)} "http://newlisp.org:80" 0)
0
> $0
"http://newlisp.org:80"
> $1
"http://"
> $2
"newlisp."
> $3
"org"
> $4
"80"
> 

Lutz

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Post by cormullion »

I see - the $0 is then the equivalent of '&' and $1 the equivalent of '\1' in other regex implementations...

Locked