如何通过分组仅捕获 Perl 正则表达式的一部分?
我目前正在尝试从文件中提取日期并将它们直接输入到数组中。我的正则表达式正在工作,但其中有 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当我下次拿起代码时,该正则表达式看起来会让我感到困惑。
我会打破它:
您可以使用 You an simple the seperator bit 将元素添加到数组中
(请注意,我已更改为使用
( )
而不是/ /
以避免必须反斜杠/
That regex looks like the sort of thing that would confuse me when I next pick up the code.
I would break it out :
You can add the element onto the array using
You an simplify the seperator bit (notice I have changed to using
( )
rather than/ /
to avoid having to backslahs the/
刚刚找到了。您可以通过在组开头使用
?:
创建被动组。通过使所有其他组处于被动状态,现在只有第一组被添加到阵列中。
just found it. You can create a passive group by using
?:
at the start of the group.by making all other groups passive, now only the first group is added to the array.