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

Hi
I have string which can hold following possible values :

$string = "abc"; $string = "abc-def"; $string = "abc_def.12"; $string = ".abc"; $string = ".abc_123"; $string = ".abcd-def"; $string = "abcd.123.def";
I need a regexp to match all these above possible combinations.
Thanks

Replies are listed 'Best First'.
Re: regex help required
by Corion (Patriarch) on Jun 24, 2013 at 07:14 UTC

    What are the relevant parts of all these combinations?

    /.*/ will match all these above possible combinations. So maybe you want to tell us what combinations are invalid.

Re: regex help required (question help too)
by Anonymous Monk on Jun 24, 2013 at 07:55 UTC
Re: regex help required
by hdb (Monsignor) on Jun 24, 2013 at 07:49 UTC
    /abc|abc-def|abc_def\.12|\.abc|\.abc_123|\.abcd-def|abcd\.123\.def/
Re: regex help required
by space_monk (Chaplain) on Jun 24, 2013 at 09:36 UTC
    You have inadequately said what you are looking for in your answer. The following will match all the above possible combinations in $result, but I strongly suspect that it is not what you want
    my $result = $string;
    If you spot any bugs in my solutions, it's because I've deliberately left them in as an exercise for the reader! :-)
Re: regex help required
by locked_user sundialsvc4 (Abbot) on Jun 24, 2013 at 13:16 UTC

    Indeed.   You must not only determine what it is you do want to match (hence the reply #1:   “what are the relevant parts?”), but also what rules will filter out what you do not want.

    Seriously consider using a subroutine to allow for some conditional logic to be used ... (pseudocode follows)

    sub my_filter { my $str = shift; my $TRUE = 1; my $FALSE = 0; # FOR CLARITY return $FALSE if ($str =~ /reject_pattern_#1/); return $FALSE if ($str =~ /reject_pattern_#2/); return $TRUE if ($str =~ /accept_pattern_#1/); return $TRUE if ($str =~ /accept_pattern_#2/); return $FALSE; // DOESN'T MATCH ANYTHING }

    Then, write a test-program using Test::More which puts your subroutine through many dozens of tests, using a carefully-chosen set of “correct,” “almost correct,” “barely incorrect” and “outright bogus” strings, to prove that your logic is actually trustworthy and reliable.   (Tip:   you will spend a lot more time ferreting-out the little bugs that were lurking in your original version, hoping to remain un-detected, than you originally thought possible.)