in reply to match whitespace or beginning/end of string

If you don't want to discombobulate your colleagues with any mention of regexen, maybe try secretly wrapping their simple patterns in whatever regex sub-patterns do the trick:
>perl -wMstrict -le "my $pre = qr{ \A | \s }xms; my $post = qr{ \s | \z }xms; my $str = q{foo='123' barfoo='987' bar='555'}; for my $user_supplied (@ARGV) { my $rx = qr{ $pre \Q$user_supplied\E $post }xms; $str =~ m{ ($rx) }xms; print qq{[$user_supplied] matches }, $1 ? qq{[$1]} : q{nothing}; } " foo='123' bar='555' barfoo='987' foo='987' [foo='123'] matches [foo='123' ] [bar='555'] matches [ bar='555'] [barfoo='987'] matches [ barfoo='987' ] [foo='987'] matches nothing
Note that the  $pre and  $post patterns can be adjusted to include as much or as little of the surrounding context (i.e., the spaces) as desired.

Replies are listed 'Best First'.
Re^2: match whitespace or beginning/end of string
by azadian (Sexton) on Nov 02, 2009 at 14:56 UTC
    That's a good idea which I hadn't thought of. Unfortunately it is not necessarily so easy to do in my application because the user is allowed to write any valid Perl regex. Maybe I can define a new class of matching which does have this wrapping.
      The approach still 'works' (in some sense) because the user can only supply the regex in the form of a string which is later compiled into and/or included into the compilation of a real regex object. Just don't use the metacharacter escaping mechanism of  \Q...\E or the quotemeta function.

      However, there seems to be another problem here: you say users may write any valid Perl regex, but you have also said (or implied) that they are not required to know anything about regexes nor to suffer any danger of exposure to such knowledge. This seems like a prescription for a major headache, if not disaster. User-supplied patterns would usually be validated or meta-quoted up the wazoo.