gpt4 book ai didi

regex - 在 Perl 中使字符串对正则表达式安全

转载 作者:行者123 更新时间:2023-12-02 05:22:45 24 4
gpt4 key购买 nike

我有一个字符串,我想在正则表达式中使用它,就像 m/$mystring_03/ 但是 $mystring 包含导致问题的 +s 和斜杠. Perl 中是否有一种简单的方法来修改 $mystring 以确保正确转义所有正则表达式通配符或其他特殊字符? (比如所有的+都变成了\+)

最佳答案

是的,使用 \Q and \E escapes :

#!/usr/bin/perl

use strict;
use warnings;

my $text = "a+";

print
$text =~ /^$text$/ ? "matched" : "didn't match", "\n",
$text =~ /^\Q$text\E$/ ? "matched" : "didn't match", "\n";

关于regex - 在 Perl 中使字符串对正则表达式安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3629229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com