Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

pattern matching with passed variable

Status
Not open for further replies.

jassiq

Technical User
Mar 15, 2003
1
US
I am passing a reg expression from a subroutine which looks like:

$regex = "/(\S+) (\S+) (\S+) \[([^\]]*)\] (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) \"([^\"]*)\" \"([^\"]*)\"/";

I am then "matching" data against it with

$line =~ $regex;

The problem is that the matching does not work if the regex is passed in from the subroutine, but does work if I create the pattern explicitly in the routine:

$line =~ /(\S+) (\S+) ... etc. as above

Any ideas as to why?

Thanks
 
Print $regex and see if it looks like what you expect. (Hint: try using single quotes around the pattern when you define it, instead.)

jaa
 
Hi,

I believe your problem lies the leading and trailing "/". This charcater is actually part of the match operation not part of the pattern to be matched.

If you remove the "/" from the beginning and end of your regular expression and place them either side in your "matching" line, it should work.

So:

$regex = "(\S+) (\S+) (\S+) \[([^\]]*)\] (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) \"([^\"]*)\" \"([^\"]*)\"";

and

$line =~/$regex/;

Eg:

$string="I am going to match the word monkey in this string";
$toMatch="monkey";

if ($string=~/$toMatch/){
print "MATCH SUCCESSFUL!!";
}else{
print"MATCH FAILED";
}

I hope this helps.

Tyger.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top