Perl 上的正则表达式来捕获这种类型的值(一)(二)

Regex on Perl to capture this type of value (a)(2)

我正在使用 perl 来捕获 HTML 文件的这一部分,例如:

我正在使用此正则表达式 ([0-9]{4}).([0-9]{4}) 来捕获此 1910.1024。但是 HTML 文件的某些部分具有这种值 1910.1024(a)(2)。我不知道用其中的值捕获这两个括号的正确方法。我将在我的 Perl 脚本中使用此正则表达式来替换此 link.

我的脚本现在正在捕获这个值 1910.1024,我想知道如何捕获这个 1910.1024(a)(2)

if($content =~ m/([0-9]{4}).([0-9]{4})/gm){
   $content =~ s/([0-9]{4}).([0-9]{4})/<!!uf dp_ecfr29 29cfrx #29cfrx>.<\/a>/gm;
}
elsif($content2 =~ m/([0-9]{4})\.([0-9]{4})(?:\((\w+)\))?(?:\((\w+)\))/gm){
   $content2 =~ s~([0-9]{4})\.([0-9]{4})(?:\((\w+)\))?(?:\((\w+)\))?~<!!uf dp_ecfr29 29cfrx #29cfrxz-->.()()</a>~g; 
}
elsif($content3 =~ m/([0-9]{4})\.([0-9]{4})(?:\((\w+)\))/gm){
   $content3 =~ s~([0-9]{4})\.([0-9]{4})(?:\((\w+)\))?~<!!uf dp_ecfr29 29cfrx #29cfrxz->.()</a>~g; 
} 
else {
   printf "Error";
}

您可以在正则表达式模式中使用几个可选的捕获组,然后在替换部分使用几个条件。

由于正则表达式很长,您可以使用 /x 标志将其分行。

参见Perl demo

#!/usr/bin/perl
use feature "say";
use strict;
use warnings;

my $content = "I am trying to capture this 1910.1024,  this 1910.1024(a) and  this 1910.1024(a)(3).";
if($content =~ m/([0-9]{4})\.([0-9]{4})/) {
   $content =~ s{
        ([0-9]{4})      #  = First 4 digits
        \.              # Dot
        ([0-9]{4})      #  = Second 4 digits
        (?:\((\w+)\))?  # (,  (first optional "word"), )
        (?:\((\w+)\))?  # (,  (second optional "word"), )
    }{
        "<!!uf dp_ecfr29 29cfrx #29cfrx" .
        (defined() ? "z-" : "") . (defined() ? "-" : "") .
        ">." . 
        (defined() ? "()" : "") . (defined() ? "()" : "") . 
        "</a>"
    }gxe;
    say "$content\n";
} else {
   say "Error";
}

输出:

I am trying to capture this <!!uf dp_ecfr29 29cfr1910x1024 #29cfr1910x1024>1910.1024</a>,  this <!!uf dp_ecfr29 29cfr1910x1024 #29cfr1910x1024z-a>1910.1024(a)</a> and  this <!!uf dp_ecfr29 29cfr1910x1024 #29cfr1910x1024z-a-3>1910.1024(a)(3)</a>.

查看 gxex 有助于将模式分成多行并添加注释,g 匹配字符串中的所有出现,e 有助于解释 RHS作为 Perl 表达式,我们可以在其中引入自定义替换逻辑。

(defined() ? "z-" : "") 等结构检查第 3 组是否匹配,然后使用一个或另一个替换文本。