in reply to Replacing numbers with links

Hi danambroseUK,

What I think you want to do is replace all of the number strings in a single, global regular expression substitute.

You could do this with, for example:

$mystring =~ s/(\d{3,5})/<b><a href='lookup.cgi?id=$1<\/a>/g;

Several things to note:  1) you can change the \d{3,5} if it turns out you have numeric strings which are less than 3 or greater than 5 digits.  2) you need to escape the '/' in <\/a>, since it would improperly terminate the regex otherwise.  3) the expression $1 is a backreference, used to specify the thing that was matched.


s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/

Replies are listed 'Best First'.
Re^2: Replacing numbers with links
by johngg (Canon) on Jul 16, 2006 at 15:36 UTC
    you need to escape the '/' in <\/a>, since it would improperly terminate the regex otherwise.

    or use something other than a forward slash as your regex delimiter, for example paired curly brackets like this

    $mystring =~ s{(\d{3,5})} {<b><a href='lookup.cgi?id=$1</a>}g;

    You often see matching against *nix paths using the default forward slash delimiter (and omitting the m as it is not required with / ... /) when using a different delimiter would be more readable.

    if( $path =~ /\/path\/to\/file/ ) { ... }

    is, I feel, much harder to read than

    if( $path =~ m{/path/to/file} ) { ... }

    Cheers,

    JohnGG

Re^2: Replacing numbers with links
by GrandFather (Saint) on Jul 16, 2006 at 17:59 UTC

    As it stands the regex will match a minimum of 3 and maximum of 5 digits, but doesn't care if they are part of a large number of digits or are imbedded in text.

    use strict; use warnings; while (<DATA>) { s|\b(\d{3,5})\b|<b><a href='lookup.cgi?id=$1</a></b>|g; print; } __DATA__ foo 300 bar bas. foo300bar bas. foo 123456 bar 1234 bas 56789. foo bar bas. 1 foo 1 bar 2 bas bas.

    Prints:

    foo <b><a href='lookup.cgi?id=300</a></b> bar bas. foo300bar bas. foo 123456 bar <b><a href='lookup.cgi?id=1234</a></b> bas <b><a href=' +lookup.cgi?id=56789</a></b>. foo bar bas. 1 foo 1 bar 2 bas bas.

    Is it a concern that the substitution introduces an orphaned bold tag for each substitution made?

    Update: fixed bold tags and changed regex delimiters to avoid picket fence


    DWIM is Perl's answer to Gödel
Re^2: Replacing numbers with links
by Anonymous Monk on Jul 16, 2006 at 18:03 UTC
    Liverpole... A perfect solution to my problem within 10minutes! It works a treat - Thats going to save me all morning tomorrow scratching my head!

    Much appricaite your help :)

    Dan