如何在Perl正则表达式中处理特殊字符? [英] How do I handle special characters in a Perl regex?
问题描述
我正在使用Perl程序从文件中提取文本.我有一个字符串数组,用作文本的分隔符,例如:
I'm using a Perl program to extract text from a file. I have an array of strings which I use as delimiters for the text, e.g:
$pat = $arr[1] . '(.*?)' . $arr[2];
if ( $src =~ /$pat/ ) {
print $1;
}
但是,数组中的两个字符串是$450
和(Buy now)
.这些问题是字符串中的符号代表Perl正则表达式中的字符串结尾和捕获组,因此文本无法按我的预期进行解析.
However, two of the strings in the array are $450
and (Buy now)
. The problem with these is that the symbols in the strings represent end-of-string and capture group in Perl regular expressions, so the text doesn't parse as I intend.
有没有办法解决这个问题?
Is there a way around this?
推荐答案
尝试Perl的 quotemeta 功能.或者,在正则表达式中使用\Q
和\E
来关闭正则表达式中的值插值.请参阅 perlretut \Q
和\E
的更多信息-它们可能不是您想要的.
Try Perl's quotemeta function. Alternatively, use \Q
and \E
in your regex to turn off interpolation of values in the regex. See perlretut for more on \Q
and \E
- they may not be what you're looking for.
这篇关于如何在Perl正则表达式中处理特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!