user2268507
user2268507

Reputation:

Regex Infinite Loop

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)

In the first line, I would like to match:

Wed 09 12

Fri 09 12

In the second line, I would like to match:

Wed 11 13

Fri 14 15

Fri 15 16

In my Perl script I have:

 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";
}

However, this is resulting in an infinite loop. I'm also not sure whether this is matching how I intend. I tried it out using RegExr (regexr.com).

Upvotes: 1

Views: 102

Answers (1)

Unihedron
Unihedron

Reputation: 11051

You should capture in a lookahead, as seen from your first expected result:

Wed 09 12

Fri 09 12

The 2nd and 3rd capturing groups will repeat.

See this regex match:

/(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]

Here is a regex demo.

Upvotes: 1

Related Questions