Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

regexp question

by hotshot (Prior)
on Feb 11, 2002 at 17:43 UTC ( [id://144656]=perlquestion: print w/replies, xml ) Need Help??

hotshot has asked for the wisdom of the Perl Monks concerning the following question:

hi fellow monks !

an easy one. how do I make my regexp test if a given string starts with a constant followed by a '/' (slash) and more characters, or no slash and no more characters. I think this will make it clearer:
my $path = '/tmp/foo'; $ex1 = '\tmp\foo\bar'; # is OK $ex2 = '\tmp\foo'; # is OK $ex3 = '\tmp\foo\'; # is OK $ex4 = '\tmp\food'; # is NOT OK
anyone?

Hotshot

Replies are listed 'Best First'.
Re: regexp question
by FoxtrotUniform (Prior) on Feb 11, 2002 at 17:58 UTC

    Untested, but should get the idea across.

    my $path =~ /^\Q$str\E # the base string; '\tmp\foo', e.g. (\\.*)? # optionally match a slash, etc. $ # match end of string /x;

    Insisting on matching $ at the end of the regex prevents you from matching "extra" chars that don't start with a backslash.

    Update: Yes, do escape the base string. (Regex updated.) Thanks Sweeper!

    --
    :wq
      I have not tested either, but I think you should escape special characters in $string:
      my $path =~ /^\Q$string\E  # the base string; '\tmp\foo', e.g.
                     (\\.*)?     # optionally match a slash, etc.
                     $           # match end of string
                    /x;
      
Re: regexp question
by hawson (Monk) on Feb 12, 2002 at 02:04 UTC
    Try this pattern:

    /^$path(?=(\/[\S\/]*|$))/

    It says, more or less: match the contents of $path, but only if followed by a slash (and optionally more slashes and non-space characters), or the end of the line. Here's my test program

    #!/usr/bin/perl -w my $path='/tmp/foo'; my @ex=('/tmp/foo', '/tmp/foo/', '/tmp/foo/bar', '/baz/tmp/foo/', '/tm +p/food'); print join(" ", grep( /^$path(?=(\/[\w\/]*|$))/, @ex)), "\n";

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://144656]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (5)
As of 2024-04-23 06:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found