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

Hi I am reading a text file which contain the following string:
"\\domca-prn01\DH4-2139-HP4"
First I need to verify that the string I am reading in has "\\" follow by either characters or numbers then "\" then either characters or numbers . I try this as:
if ( $string =~ /\\\\.*\\.*/) { print"match\n"; }
The problem I am having is getting the string that exist after the single "\" in this situation the string "DH4-2139-HP4". I am thinking backreference maybe the answer. -----thanks thanks in advance.

Replies are listed 'Best First'.
Re: pattern matching problem
by sgifford (Prior) on Jul 22, 2003 at 16:46 UTC
    It sounds like backreferences would do just what you want:
    if ( $string =~ /\\\\([\w-]+)\\([\w-]+)/) { print"match: \$1=$1, \$2=$2\n"; }

    I changed your regex to be closer to what you described in the text; it only matches letters, numbers, underscores, and - between the backslashes, and requires at least one character (something like \\\ would have passed your previous regex). If that's not what you want, change it back, but put parentheses around your .*'s.

Re: pattern matching problem
by dga (Hermit) on Jul 22, 2003 at 17:10 UTC

    Something like this might work.

    use strict; use warnings; while(<>) { chop; my($id) = /\\\\.+\\(.+)/; print "$id\n" if($id); }

    In the regular expression I use ()'s to group and capture, then because I used ()'s on the my, it puts a list context onto the assignment and so the RE returns a list of the captured values. In this case the first captured element returned is assigned to $id. I then use $id normally to print out the ID if the RE matched. On a non match $id is undef.

    I tested with a tiny test case of:

    \\domca-prn01\DH4-2139-HP4 \\vlasd \\\dsasd \test\ing

    Only the identifier from the first line of the test file is output.

Re: pattern matching problem
by roju (Friar) on Jul 22, 2003 at 16:48 UTC
    Eep. .*? Try to specify the string as clearly as possible in your regex. So something like /\\\\[[:alnum:]]+\\([[:alnum:]]+)/; print $1;