在Perl中如何使用变量作为正则表达式修饰符? [英] How do I use a variable as a regex modifier in perl?
问题描述
sub ask {
my($ prompt,$ validationRe,$ caseSensitive)= @_ ;
我的$ modifier =($ caseSensitive)? : 一世;
我的$ ans;
我的$ isValid;
do {
print $ prompt;
$ ans =<> ;;
chomp($ ans);
#我想做什么不起作用:
#$ isValid = $ ans =〜/ $ validationRe / $ modifier;
#我必须做的:
$ isValid =($ caseSensitive)?
($ ans =〜/ $ validationRe /):
($ ans =〜/ $ validationRe / i);
} while(!$ isValid);
return $ ans;
}
Upshot:是否有任何方式动态指定正则表达式的修饰符? p>
Upshot:有没有办法动态指定正则表达式的修饰符?
从 perldoc perlre
:
(?adlupimsx-imsx)
(?^ alupimsx)
要打开的一个或多个嵌入式模式匹配修饰符(或
关闭,如果前面带有 - ),或者
是封闭模式组的其余部分(如果有的话)。
这是特别有用的对于动态模式,例如从配置文件读取
,从参数中获取,或在
a表中指定的动态模式。考虑一些模式想要成为
区分大小写的情况,有些不需要:不区分大小写的只需要
在模式的前面包含(?i)。
这给你一些沿着
$ isValid = $ ans =〜m /(?$ modifier)$ validationRe /;
只有在以这种方式接受用户输入时,请务必采取适当的安全预防措施。
I'm writing an abstraction function that will ask the user a given question and validate the answer based on a given regular expression. The question is repeated until the answer matches the validation regexp. However, I also want the client to be able to specify whether the answer must match case-sensitively or not. So something like this:
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 any way to dynamically specify a regular expression's modifiers?
Upshot: is there any way to dynamically specify a regular expression's modifiers?
From 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.
Which gives you something along the lines of
$isValid = $ans =~ m/(?$modifier)$validationRe/;
Just be sure to take the appropriate security precautions when accepting user input in this way.
这篇关于在Perl中如何使用变量作为正则表达式修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!