Perl 正则表达式中的转义特殊字符
我正在尝试匹配 Perl 中的正则表达式。我的代码如下所示:
my $source = "Hello_[version]; Goodbye_[version]";
my $pattern = "Hello_[version]";
if ($source =~ m/$pattern/) {
print "Match found!"
}
问题出现在当 Perl 尝试匹配正则表达式时,括号指示字符类(或者我读到的字符类),并且匹配最终失败。我知道我可以使用 \[
或 \]
转义括号,但这需要另一个代码块来遍历字符串并搜索括号。有没有办法自动忽略括号而不单独转义它们?
快速注意:我不能只添加反斜杠,因为这只是一个示例。在我的真实代码中,$source
和 $pattern
都来自 Perl 代码外部(URIEncoded 或来自文件)。
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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
\Q
将禁用元字符,直到找到\E
或模式末尾。http://www.anaesthetist.com/mnm/perl/Findex.htm
\Q
will disable metacharacters until\E
is found or the end of the pattern.http://www.anaesthetist.com/mnm/perl/Findex.htm
使用 quotemeta():
Use quotemeta():
您使用了错误的工具来完成这项工作。
你没有模式!没有正则表达式
$pattern 中的字符!
你有一个文字字符串。
index() 用于处理文字字符串...
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...
您可以使用以下命令转义表达式中的特殊字符集。
You can escape set of special characters in an expression by using the following command.