如何通过分组仅捕获 Perl 正则表达式的一部分?

发布于 2024-08-29 22:10:00 字数 374 浏览 10 评论 0原文

我目前正在尝试从文件中提取日期并将它们直接输入到数组中。我的正则表达式正在工作,但其中有 6 个组,所有这些组都被添加到数组中,而我只想要第一个组。

@dates = (@dates, ($line =~ /((0[1-9]|[12][0-9]|3[01])(\/|\-)(0[1-9]|1[0-2])(\/|\-)([0-9][0-9][0-9][0-9]|[0-9][0-9]))/g ));

有没有一种简单的方法来获取 Perl 正则表达式的 $1 组?

我的输出如下所示:

13/04/2009, 13, /, 04, /, 2009, 14-12-09, 14, -, 12, -, 09

I've currenly trying to pull out dates from a file and feed them directly into an array. My regex is working, but I have 6 groups in it, all of which are being added to the array, when I only want the first one.

@dates = (@dates, ($line =~ /((0[1-9]|[12][0-9]|3[01])(\/|\-)(0[1-9]|1[0-2])(\/|\-)([0-9][0-9][0-9][0-9]|[0-9][0-9]))/g ));

is there a simple way to grab the $1 group of a perl regex?

my output is looking like this:

13/04/2009, 13, /, 04, /, 2009, 14-12-09, 14, -, 12, -, 09

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淡水深流 2024-09-05 22:10:00

当我下次拿起代码时,该正则表达式看起来会让我感到困惑。
我会打破它:

    my $date= qr/
       (?:0[1-9]|[12][0-9]|3[01])           # day
       (?:\/|\-)
       (?:0[1-9]|1[0-2])                    # month
       (?:\/|\-)
       (?:[0-9][0-9][0-9][0-9]|[0-9][0-9])  #year
       /x ;

您可以使用 You an simple the seperator bit 将元素添加到数组中

    push @dates,   ($line =~ /($date)/ ) ;

(请注意,我已更改为使用 ( ) 而不是 / / 以避免必须反斜杠 /

    my $date= qr (
       (?: 0[1-9] | [12][0-9] | 3[01]       # day
       [/-]
       (?:0[1-9]|1[0-2])                    # month
       [/-]
       (?:\d{4}|\d{2})                      #year
       )x ;

That regex looks like the sort of thing that would confuse me when I next pick up the code.
I would break it out :

    my $date= qr/
       (?:0[1-9]|[12][0-9]|3[01])           # day
       (?:\/|\-)
       (?:0[1-9]|1[0-2])                    # month
       (?:\/|\-)
       (?:[0-9][0-9][0-9][0-9]|[0-9][0-9])  #year
       /x ;

You can add the element onto the array using

    push @dates,   ($line =~ /($date)/ ) ;

You an simplify the seperator bit (notice I have changed to using ( ) rather than / / to avoid having to backslahs the /

    my $date= qr (
       (?: 0[1-9] | [12][0-9] | 3[01]       # day
       [/-]
       (?:0[1-9]|1[0-2])                    # month
       [/-]
       (?:\d{4}|\d{2})                      #year
       )x ;
-小熊_ 2024-09-05 22:10:00

刚刚找到了。您可以通过在组开头使用 ?: 创建被动组。

@dates = (@dates, ($line =~ /((?:0[1-9]|[12][0-9]|3[01])(?:\/|\-)(?:0[1-9]|1[0-2])(?:\/|\-)(?:[0-9][0-9][0-9][0-9]|[0-9][0-9]))/g ));

通过使所有其他组处于被动状态,现在只有第一组被添加到阵列中。

just found it. You can create a passive group by using ?: at the start of the group.

@dates = (@dates, ($line =~ /((?:0[1-9]|[12][0-9]|3[01])(?:\/|\-)(?:0[1-9]|1[0-2])(?:\/|\-)(?:[0-9][0-9][0-9][0-9]|[0-9][0-9]))/g ));

by making all other groups passive, now only the first group is added to the array.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文