在Perl中如何使用变量作为正则表达式修饰符? [英] How do I use a variable as a regex modifier in perl?

查看:684
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆