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

Hello, I have a quick regex question. How would i match anything up until the 3rd under score and store it in an var? So for a file name, everything up until the 3rd _. Thanks in advance.

Replies are listed 'Best First'.
Re: Quick regex
by BrowserUk (Patriarch) on Nov 24, 2009 at 17:14 UTC

    Like this?

    $s = 'fred_bill_john_jack_joe_mary_eugene';; $s =~ /(^[^_]+_[^_]+_[^_]+_)/ and print "'$1'";; 'fred_bill_john_'

    Or this?

    $s =~ /(^(?:[^_]+_){3})/ and print "'$1'";; 'fred_bill_john_'

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      that looks good, but how do i kill the trailing _ So your example would look like this 'fred_bill_john'

        You want to match

        name, dash, name, dash, name

        or

        ( name, dash ) x 2, name

        so

        my ($substr) = $s =~ /^((?:[^_]*_){2}[^_]*)/ or die("No match\n");
        Everything in ( ) goes into $1, so move the last _ outside of )
Re: Quick regex
by Anonymous Monk on Nov 24, 2009 at 17:10 UTC
    This is probably faq
    print $1 if "ab _ cd _ ef _ gh " =~ /(.*?(_).*?\2.*?)\2/; __END__ ab _ cd _ ef