[Nottingham] Perl Regular Expression Query.

nottingham@mailman.lug.org.uk nottingham at mailman.lug.org.uk
Fri Jan 17 14:12:00 2003


Hi,

On Fri, 17 Jan 2003, Robert Postill wrote:
> I'm writing some Perl and want to match a string with 4 @ signs
> separated by a variable number of characters.  Currently I'm trying:
> /@.*?@.*?@.*?@/ Which is not matching the strings properly.  Has anyone
> any idea what's wrong?  More importantly has anyone got a way of fixing
> it? :)

I'm not by any imagination a perl programmer but from what I know about
regex, the '?'s are erroneous. You should be using /@.*@.*@.*@/, in fact
using s2p for sed 's/@.*@.*@.*@/crap/' gives

---8<---
#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
        if $running_under_some_shell;

while ($ARGV[0] =~ /^-/) {
    $_ = shift;
  last if /^--/;
    if (/^-n/) {
        $nflag++;
        next;
    }
    die "I don't recognize this switch: $_\\n";
}
$printit++ unless $nflag;

$\ = "\n";              # automatically add newline on print

LINE:
while (<>) {
    chop;
    s/@.*@.*@.*@/crap/;
    print if $printit;
}
---8<---

and saving that as scrap.pl then allows us to test it.

$ echo -e '@@@@\none@two@three@four@\n@a@b@c@d' | perl scrap.pl
crap
onecrap
crapd

hth,
 Peter