在Perl正则表达式中转义特殊字符 [英] Escaping special characters in Perl regex
问题描述
my $ source =Hello_ [version]; Goodbye_ [version];
我的$ pattern =Hello_ [version];
if($ source =〜m / $ pattern /){
printMatch found!
}
问题出现在括号中,表示一个字符类(或者我读到的)当Perl尝试匹配正则表达式时,匹配结果将失败。我知道我可以用 \ [
或 \]
摆脱括号,但这将需要另一个代码通过字符串搜索括号。有没有一种方法可以自动忽略括号,而不会单独转义它们?
快速注意:我不能添加反斜杠,因为这只是一个例子。在我的真实代码中, $ source
和 $ pattern
都来自Perl代码外(URIEncoded或从文件)。
您正在使用错误的工具作为。
你没有图案! $ pattern中没有正则表达式
个字符!
您有一个文字字符串。
索引()用于处理文字字符串...
my $ source =Hello_ [version]; Goodbye_ [version] ;
我的$ pattern =Hello_ [version];
if(index($ source,$ pattern)!= -1){
printMatch found!;
}
I'm trying to match a regular expression in Perl. My code looks like the following:
my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = "Hello_[version]";
if ($source =~ m/$pattern/) {
print "Match found!"
}
The problem arises in that brackets indicate a character class (or so I read) when Perl tries to match the regex, and the match ends up failing. I know that I can escape the brackets with \[
or \]
, but that would require another block of code to go through the string and search for the brackets. Is there a way to have the brackets automatically ignored without escaping them individually?
Quick note: I can't just add the backslash, as this is just an example. In my real code, $source
and $pattern
are both coming from outside the Perl code (either URIEncoded or from a file).
You are using the Wrong Tool for the job.
You do not have a pattern! There are NO regex characters in $pattern!
You have a literal string.
index() is for working with literal strings...
my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = "Hello_[version]";
if ( index($source, $pattern) != -1 ) {
print "Match found!";
}
这篇关于在Perl正则表达式中转义特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!