regex - 序列 (? 正则表达式不完整 - 负面环视

标签 regex perl

在使用 Jeffrey Friedl 的书《精通正则表达式》第 3 版中的“negative lookaround”代码运行我的 perl 脚本时,我遇到了以下错误。 (第 167 页)。谁能帮我解决一下??

错误信息:

序列 (? 在正则表达式中不完整;在 m/中用 <-- HERE 标记 ( ( (? <-- 这里/在/home/wubin28/mastering_regex_cn/p167.pl 第 13 行。

我的 perl 脚本

#!/usr/bin/perl

use 5.006;
use strict;
use warnings;

my $str = "<B>Billions and <B>Zillions</B> of suns";

if ($str =~ m!
    (
        <B>
        (
            (?!<B>) ## line 13
            .
        )*?
        </B>
    )
    !x
    ) {
    print "\$1: $1\n"; #output: <B>Billions and <B>Zillions</B>
} else {
    print "not matched.\n";
}

最佳答案

你使用 symbol 的错误!用于打开和关闭正则表达式,同时使用否定前瞻 (?!.)。如果您将打开和关闭符号更改为 { 和 },或//。您的正则表达式评估正常。

use strict;

my $str = "<B>Billions and <B>Zillions</B> of suns";

if ($str =~ m/(<B>((?!<B>).)*?<\/B>)/x) {
    print "\$1: $1\n"; #output: <B>Billions and <B>Zillions</B>
} else {
    print "not matched.\n";
}

关于regex - 序列 (? 正则表达式不完整 - 负面环视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11131356/

相关文章:

python - 将字符串重新渲染为原始字符串

perl - 为什么 Perl 允许通过引用传递参数?

PHP str_replace 空格的任意组合

逗号分隔小数的 Javascript 正则表达式

regex - 识别特殊字符

perl - 在命令行上解析HTML;如何在<strong> </strong>中捕获文本?

perl - 如何在 PerlMagick 中居中字幕?

Perl远程写文件连接报错Net::SFTP::Foreign

perl - 为什么安装带有 perl 模块的程序硬编码 perl 版本?

mysql - 无法找到一种方法来否定模式内的正则表达式