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 Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pattern Matching - Using a variable 2

Status
Not open for further replies.

glwong

Programmer
Jul 13, 2001
15
US
I am storing a line of charcaters in a variable
($line) and am trying to search a buffer
for the pattern. I have two issues,

1)
The buffer contains $line but it is preceded
by extra characters (for example 123456$line)

2)
Is there a way to search the buffer using
the variable ($line)? In essence I want to


$buffer =~ /*($variable)/;

but I know that is the wrong syntax, is there
a way to achieve my goal?

Thanks,
Greg
 
How about

if ($buffer =~ /$variable/) {
### found $variable in $buffer - do something
}
else {
### did *NOT* find $variable in $buffer - do something else
}

Does this answer your question? To find more info on Perl regular expressions, do "perldoc perl" and look for regular expression topics - Perl 5.6.1 has these topics:

perlrequick Perl regular expressions quick start
perlretut Perl regular expressions tutorial
perlre Perl regular expressions, the rest of the story

HTH.
Hardy Merrill
Mission Critical Linux, Inc.
 
If you don't care where in $buffer the variable $line occurs, just that it occurs somewhere, try this one:
Code:
$buffer =~ /$line/;
If you know that the value of $line is not going to change, you can gain a little efficiency by adding o after the final /

If you want to make sure that $line occurs only at the end of $buffer, this will do it:
Code:
$buffer =~ /$line$/;
Note that the trick with using variables is that they're not the last thing in the regex (otherwise they look like an end-of-line test), and the variable actually exists. Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
 
I've found that there are problems in matching strings in variables if the string you are trying to match contain slashes. Say if you are trying to match " C:\blah\blah1 " and you store this into a variable. Something like:

$variable = 'c:/blah/blah1';
$buffer =~ m/$variable/;

or

$variable = "c:\\blah\\blah1";
$buffer =~ m/$variable/;


I've tried using "/" slash also "\\" but still does not seem to work properly. I wonder if any1 have this problem as well.
 
Not sure why the second one won't work, but in the first case why don't you slap a different pair of regexp delimiters around $variable;

summat like;

$variable = "c:/blah/blah";
$buffer =~ m|$variable|;
 
shoot good idea! why didnt i think of that heh 8)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top