[tpm] New Regex question

Chris Jones cj at enersave.ca
Sun Oct 28 11:23:33 PDT 2012

At 07:22 PM 27/10/2012, Uri Guttman wrote:
>On 10/27/2012 06:57 PM, Rob Janes wrote:
>>$1 doesn't work.
>>\1 is the characters matched while $1 is the pattern matched.
>>It only matters if u want to match pure string.
>that is wrong. both are only references to a grab which is always a 
>string. you can use \1 in the regex to match what you have 
>previously matched and grabbed. $1 is used in the replacement or 
>after the regex to get what was grabbed. neither contains a regex.

Chapman states that \1 is used with in the pattern and $1 is used 
everywhere else.  He offers this example:

    s/(\w+ and \1/$1 twice/;
    s/(w+) and (\w+)/$2 and $1/;

This example reverses pairs of different words, 'Marks and Spencer' 
into 'Spencer and Marks', and collapses identical pairs, taking 
'Sattchi and Sattchi' into 'Sattchi twice'

So, my example should be $exp =~ s/(\s|\r\n)\1+/$1/g;

Christopher Jones, P.Eng.
Suite 1801, 1 Yonge Street
Toronto, ON M5E1W7
Tel. 416-203-7465
Fax. 416-946-1005
email cj at enersave.ca

More information about the toronto-pm mailing list