正则表达式无限循环

时间:2014-09-18 12:24:08

标签: regex perl loops

ABCD1234: X1 Wed, Fri 09:00 - 12:00 (Weeks:1-8)

ACD1234: S1 Wed 11:00 - 13:00 (Weeks:1-7,8-12), Fri 14:00 - 15:00 (Weeks:1-7,8-12), Fri 15:00 - 16:00 (Weeks:1-7,8-12)

在第一行,我想匹配:

Wed 09 12

Fri 09 12

在第二行,我想匹配:

Wed 11 13

Fri 14 15

Fri 15 16

在我的Perl脚本中,我有:

 while ($line =~ m/(Mon|Tue|Wed|Thu|Fri).+?([0-9][0-9]):.+?- ([0-9][0-9])/){

    print "$1\n";
    print "$2\n";
    print "$3\n";
}

然而,这导致无限循环。我也不确定这是否符合我的意图。我用RegExr(regexr.com)试了一下。

1 个答案:

答案 0 :(得分:1)

从第一个预期结果中可以看出,你应该进行一次预测:

Wed 09 12

Fri 09 12

第二和第三个捕获组将重复。

请参阅此正则表达式匹配:

/(Mon|Tue|Wed|Thu|Fri)(?=.+?([0-9][0-9]):.+?- ([0-9][0-9]))/g
ABCD1234: X1 Wed, Fri 09:00 - 12:00 (Weeks:1-8)

ACD1234: S1 Wed 11:00 - 13:00 (Weeks:1-7,8-12), Fri 14:00 - 15:00 (Weeks:1-7,8-12), Fri 15:00 - 16:00 (Weeks:1-7,8-12)
Match 1: [Group 1: Wed][Group 2: 09][Group 3: 12]
Match 2: [Group 1: Fri][Group 2: 09][Group 3: 12]
Match 3: [Group 1: Wed][Group 2: 11][Group 3: 13]
Match 4: [Group 1: Fri][Group 2: 14][Group 3: 15]
Match 5: [Group 1: Fri][Group 2: 15][Group 3: 16]

这是regex demo