Highlighting Special Characters in a Perl Regular Expression

I am trying to match a regex in Perl. My code is as follows:

my $source = "Hello_[version]; Goodbye_[version]"; my $pattern = "Hello_[version]"; if ($source =~ m/$pattern/) { print "Match found!" } 

The problem is that the class of characters is indicated in brackets (or so I read) when Perl tries to match the regular expression, and the match fails. I know that I can escape the brackets with \[ or \] , but this will require another block of code to traverse the line and search for the braces. Is there any way that parentheses are automatically ignored without leaving them individually?

Quick note: I can't just add a backslash, as this is just an example. In my true code, $source and $pattern both come from outside Perl code (either URIEncoded, or from a file).

+6
source share
5 answers

You use the Wrong tool for the job.

You have no template! No regex characters in $ pattern!

You have a literal string.

index () is designed to work with literal strings ...

 my $source = "Hello_[version]; Goodbye_[version]"; my $pattern = "Hello_[version]"; if ( index($source, $pattern) != -1 ) { print "Match found!"; } 
+10
source

Use quotemeta () :

 my $source = "Hello_[version]; Goodbye_[version]"; my $pattern = quotemeta("Hello_[version]"); if ($source =~ m/$pattern/) { print "Match found!" } 
+11
source

\Q will disable the metacharacters until \E or the end of the pattern is found.

 my $source = "Hello_[version]; Goodbye_[version]"; my $pattern = "Hello_[version]"; if ($source =~ m/\Q$pattern/) { print "Match found!" } 

http://www.anaesthetist.com/mnm/perl/Findex.htm

+11
source

You can avoid typing special characters in an expression by using the following command.

expression1 = 'text with special characters such as $% ()';

expression1 = ~ s / [\? * + \ ^ \ $ [] \ () {} \ | -] / "\ $ &" / eg;

This avoids all special characters.

print "expression1 '; # text with special characters such as \ $ \% ()

0
source

The quote $pattern defeats the purpose of regular expressions, unless it is used as a well-known literal and dumped into a real regular expression.

change
Otherwise, just use index() to find the position of the substring. With this information, just use substr() to retrieve the surrounding data, if necessary.

-1
source

Source: https://habr.com/ru/post/897349/


All Articles