Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: Regex to get everything before first /

by davido (Cardinal)
on Jun 06, 2011 at 19:18 UTC ( #908355=note: print w/replies, xml ) Need Help??

in reply to Regex to get everything before first /

toolic hit the nail on the head, but you might choose a different delimiter so that it wouldn't be necessary to escape the forward slash, like this:

my $thing = 'foo/bar/goo'; ( my $stuff ) = ( $thing =~ m{ # Quote-like characters are now {}. ^ # Match at the start of the string. ( [^/]+ ) # Capture everything in the set of all # characters that are not '/' }x # Close the regexp. x modifier allows # freeform (as in non-significant # whitespace). ); print "$stuff\n";

The m{} brackets avoid the leaning toothpick syndrome in the original regexp. Of course if you were matching against a curly bracket the curly brackets wouldn't be all that wonderful as quote delimiters, but for this regexp they work out well. /x modifier added to allow comments and insignificant whitespace (it makes everything prettier).


Replies are listed 'Best First'.
Re^2: Regex to get everything before first /
by JavaFan (Canon) on Jun 06, 2011 at 19:44 UTC
    /x modifier added to allow comments and insignificant whitespace (it makes everything prettier).
    And it's easy to get carry it too far. I find /([^\/]*)/ far superior to your novella.

    There's a guide line to not overdo comments. That's, don't do:

    $i++; # Increment $i by one, or to the next "word".
    That holds for patterns as well.

      I see a difference between explaining what I'm doing to someone who was having difficulty with a fairly straightforward regexp, in the context of a learning environment, and producing clear, concise, readable code in a non-instructional environment. A novella to an experienced user may be useful guidance to someone with less familiarity on the topic.

      It could also be said that YAPE::Regex::Explain produces too much explanation. Yet when it's requested, it's available. Should someone comment the trivial in a normal script (whatever normal means)? No. Could excessive comments be helpful in the context of describing how a specific segment of code works to someone who has requested instruction? Yes.

      Anyway, the code and comments were provided with the intent of being helpful, and I believe that goal was probably accomplished.


        Thanks Dave. It is helpful and understood. I hate code explanations that are packed with shortcuts and tricks that obfuscate the concept.
      A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://908355]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2021-01-25 01:33 GMT
Find Nodes?
    Voting Booth?