in reply to RegExp Matched Values

Use $string =~ m/^(frm)(\w+?)(txt)?$/;. This works because \w+? tries to match the smallest possible string now

Note this works only because the string is anchored at the end. Otherwise \w+? would always match only one character and (txt)? the empty string.

Replies are listed 'Best First'.
Re^2: RegExp Matched Values
by AnomalousMonk (Archbishop) on Apr 30, 2010 at 14:43 UTC
    $string =~ m/^(frm)(\w+?)(txt)?$/;

    There's a problem here in that if  'txt' may not be present (as  (txt)? implies) and an overall match is still desired,  $3 will be undefined because the third capture group need not match at all. A different approach will yield an empty string instead.

    >perl -wMstrict -le "for (@ARGV) { m/^(frm)(\w+?)(txt)?$/; print qq{'$_' ($1) ($2) ($3)}; } print '-----------'; for (@ARGV) { m/^(frm)(\w+?)(txt|)$/; print qq{'$_' ($1) ($2) ($3)}; } " frmNametxt frmNameFoo 'frmNametxt' (frm) (Name) (txt) Use of uninitialized value $3 in concatenation (.) or string at ... 'frmNameFoo' (frm) (NameFoo) () ----------- 'frmNametxt' (frm) (Name) (txt) 'frmNameFoo' (frm) (NameFoo) ()