regex - 使用 | 时两种选择是否匹配?在 Perl 正则表达式中?

标签 regex perl

我对下面的正则表达式感到困惑。请帮助我理解它。

my $test = "fred andor berry";
if ($test =~ /fred (and|or) berry/) {
    print "Matched!\n";
} else {
      print "Did not match!\n";
}

我认为它会匹配,但我得到“不匹配!”。如果我添加 +在里面,像这样,
my $test = "fred andor berry";
if ($test =~ /fred (and|or)+ berry/) {
   print "Matched!\n";
} else {
   print "Did not match!\n";
}

然后它匹配。我以为我可以用 and|or匹配带有“and”、“or”和“andor”的表达式。不?

最佳答案

正则表达式的一部分是 (and|or)表示匹配“和”或“或”,但不能同时匹配。当您将加号附加到该组时,它可以匹配一次或多次。例如,“fred andandandand berry”也是 /fred (and|or)+ berry/ 的有效匹配项。

关于regex - 使用 | 时两种选择是否匹配?在 Perl 正则表达式中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7265674/

相关文章:

RegEx 确保字符串至少包含一个小写字符、大写字符、数字和符号

ruby - 用于检测数字序列的正则表达式

javascript - 正则表达式将 <div> 转换为 <br>

perl - 从 cpan 安装 List-SomeUtils 时出错

database - 我如何从 Yahoo! 获取和比较股票报价?和谷歌?

regex - 将字符串拆分为多个分隔符

regex - 如何使正则表达式仅搜索 ipv4 地址?

perl - 如何将稍后创建的小部件对象发送到 Tk 中的回调?

perl - Perl 中的垃圾收集

perl - 你如何在 Perl 中编写 OAuth2 服务器?