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

Using a variable with regular expression

Status
Not open for further replies.

mountainbiker

Programmer
Aug 21, 2002
122
GB
Say we have a pattern we want to match. This pattern is used many times in the program. For this example, lets say this is what we have:

/\d{8}.*\.html/;

Now lets make the pattern a variable, so the following would work:

$pattern = "\\d{8}.*\\.html";
/$pattern/;

Problem:
How can we avoid having to escape the '\' or other metachars in $pattern?
 
MountainBiker

You can avoid having to quote / chars by using a different delimiter, like this:

s~search_string~replacement_text~;

You can't, as far as I know, avoid having to replace metachars in the search string itself. Mike

"Experience is the comb that Nature gives us, after we are bald."

Is that a haiku?
I never could get the hang
of writing those things.
 
Here's what I what I ended up using

$file = "2002hello.html";

$pattern = q!\d{4}!; # instead of "\\d{4}"

if ($file =~ m/$pattern/){
print "a match\n";
} else {
print "NO match\n";
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top