You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Perl如何将正则表达式的多个匹配结果及位置打印在同一行

Perl实现逐行正则匹配并输出所有匹配结果及位置

原代码的核心问题

  • 没有给正则加 /g 全局匹配修饰符,只能拿到每行第一个匹配结果
  • 标量上下文下 $line =~ /$re/ 仅返回匹配是否成功的布尔值,不是匹配总次数
  • 输入的正则带前后的 / 符号,未剥离会导致匹配逻辑错误
  • @- 数组的下标对应当前匹配的捕获分组序号,不是多轮匹配的序号,不能用来计数多匹配结果

完整可运行实现

use strict;
use warnings;

# 接收用户输入的正则
print "Enter a reg expression => ";
my $re_input = <>;
chomp $re_input;

# 提取/包裹的正则主体,兼容输入格式
my ($re) = $re_input =~ m{^/(.*)/$};
die "输入格式错误,请使用 /正则表达式/ 格式输入" unless defined $re;

# 逐行读取目标文件,可自行替换为open打开的指定文件句柄
my $line_no = 0;
while (my $content = <>) {
    $line_no++;
    my @match_res;

    # 全局匹配循环获取所有匹配项
    while ($content =~ /$re/g) {
        push @match_res, {
            val => $&,
            pos => $-[0]
        };
    }

    # 按要求格式输出
    if (@match_res) {
        my $count = scalar @match_res;
        print "Line $line_no has $count match(es) with starting location(s) shown:\n";
        print join("    ", map { "$_->{val} [$_->{pos}]" } @match_res) . "\n";
    }
}

使用说明

将代码保存为regex_match.pl,待匹配的文件保存为test.txt,执行命令:
perl regex_match.pl test.txt
按照提示输入正则(比如/\d{3}/),即可得到符合要求的输出格式。

内容的提问来源于stack exchange,提问作者Bảo Vương

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 04:39:01