我正在尝试匹配Perl中的正则表达式。我的代码如下所示:
my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = "Hello_[version]";
if ($source =~ m/$pattern/) {
print "Match found!"
}
当Perl尝试匹配正则表达式时,出现的问题是括号表示字符类(或我读到的),并且匹配以失败告终。我知道我可以用[
或]
转义括号,但这将需要另一个代码块来遍历字符串并搜索括号。有没有一种方法可以自动忽略括号而不单独转义它们?
快速注意:我不能只是添加反斜杠,因为这只是一个例子。在我的实际代码中,$source
和$pattern
都来自Perl代码外部(URIEncoded或来自文件)。
Q
将禁用元字符,直到找到E
或模式结束。
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 Use quotemeta():
my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = quotemeta("Hello_[version]");
if ($source =~ m/$pattern/) {
print "Match found!"
}
您使用了错误的工具。
你没有模式!没有正则表达式$pattern中的字符!
你有一个字面值字符串。
index()用于处理字面值字符串…
my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = "Hello_[version]";
if ( index($source, $pattern) != -1 ) {
print "Match found!";
}
可以使用以下命令转义表达式中的一组特殊字符。
expression1 = 'text with special characters like $ % ( )';
expression1 =~s/[?*+^$[]\(){}|-]/"\$&"/eg ;
#This will escape all the special characters
print "expression1'; # text with special characters like $ % ( )