gpt4 book ai didi

regex - 如何在Perl中将变量用作正则表达式修饰符?

转载 作者:行者123 更新时间:2023-12-04 05:17:53 30 4
gpt4 key购买 nike

我正在编写一个抽象函数,该函数将向用户提出一个给定的问题,并根据给定的正则表达式验证答案。重复该问题,直到答案与验证正则表达式匹配为止。

但是,我也希望客户端能够指定答案是否必须区分大小写。

所以像这样:

sub ask {
my ($prompt, $validationRe, $caseSensitive) = @_;
my $modifier = ($caseSensitive) ? "" : "i";
my $ans;
my $isValid;

do {
print $prompt;
$ans = <>;
chomp($ans);

# What I want to do that doesn't work:
# $isValid = $ans =~ /$validationRe/$modifier;

# What I have to do:
$isValid = ($caseSensitive) ?
($ans =~ /$validationRe/) :
($ans =~ /$validationRe/i);

} while (!$isValid);

return $ans;
}

结果:有没有一种方法可以动态指定正则表达式的修饰符?

最佳答案

Upshot: is there a way to dynamically specify a regular expression's modifiers?



perldoc perlre:

"(?adlupimsx-imsx)" "(?^alupimsx)" One or more embedded pattern-match modifiers, to be turned on (or turned off, if preceded by "-") for the remainder of the pattern or the remainder of the enclosing pattern group (if any).

This is particularly useful for dynamic patterns, such as those read in from a configuration file, taken from an argument, or specified in a table somewhere. Consider the case where some patterns want to be case-sensitive and some do not: The case-insensitive ones merely need to include "(?i)" at the front of the pattern.



这给你一些类似的东西
$isValid = $ans =~ m/(?$modifier)$validationRe/;

以这种方式接受用户输入时,只需确保采取适当的安全预防措施即可。

关于regex - 如何在Perl中将变量用作正则表达式修饰符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27576498/

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