Bod has asked for the wisdom of the Perl Monks concerning the following question:
I thought I was OK with basic regular expressions, but the behaviour of this has bamboozled me...
Can you please explain what I am doing wrong?
perl -e "my $test = join ', ', ('A', 'B', 'C');$test =~ s/,(.+?)$/ and +$1/; print $test;"
The result I want is for the list to have a comma separating each item except the last two items which will be separated by 'and'. So the results should be along these lines:
A -> A
A, B -> A and B
A, B, C -> A, B and C
However, the result of the one liner above is A and B, C
I expected ,(.+?)$ to match a comma followed by the shortest possible text and the end of the string. I expected (.+?) to match ' C' as that is the shortest possible match and ? is used to make the match non-greedy
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Non-greedy substitution
by choroba (Cardinal) on Nov 15, 2024 at 20:12 UTC | |
by Bod (Parson) on Nov 15, 2024 at 21:35 UTC | |
by LanX (Saint) on Nov 18, 2024 at 02:18 UTC | |
by Bod (Parson) on Nov 21, 2024 at 23:14 UTC | |
by LanX (Saint) on Nov 22, 2024 at 15:31 UTC | |
| |
by Bod (Parson) on Nov 15, 2024 at 21:46 UTC | |
by Corion (Patriarch) on Nov 15, 2024 at 21:53 UTC | |
|
Re: Non-greedy substitution
by tybalt89 (Monsignor) on Nov 15, 2024 at 20:42 UTC | |
|
Re: Non-greedy substitution
by ikegami (Patriarch) on Nov 15, 2024 at 19:19 UTC | |
by Bod (Parson) on Nov 15, 2024 at 19:38 UTC | |
by ikegami (Patriarch) on Nov 15, 2024 at 20:00 UTC | |
by Bod (Parson) on Nov 15, 2024 at 21:38 UTC | |
by ikegami (Patriarch) on Nov 18, 2024 at 01:34 UTC | |
by Bod (Parson) on Nov 15, 2024 at 19:27 UTC | |
by ikegami (Patriarch) on Nov 15, 2024 at 19:55 UTC | |
by Paladin (Vicar) on Nov 15, 2024 at 19:58 UTC | |
by ikegami (Patriarch) on Nov 15, 2024 at 20:14 UTC | |
|
Re: Non-greedy substitution
by LanX (Saint) on Nov 15, 2024 at 22:33 UTC | |
by LanX (Saint) on Nov 16, 2024 at 08:17 UTC | |
|
Re: Non-greedy substitution
by jwkrahn (Abbot) on Nov 15, 2024 at 23:50 UTC | |
|
Re: Non-greedy substitution
by sleet (Pilgrim) on Nov 15, 2024 at 23:54 UTC |