But what does your RegExp actually match? (Also a 'fixed' version based on what I think you think you want.)
c:\@Work\Perl\monks>perl -wMstrict -le "$_ = 'Three, Four, One, Two'; ;; /([A-Z][a-z][.][\b])/; print qq{'$1' '$2' '$3' '$4'}; ;; /([A-Z] [a-z]+ (?: , | \b))/x; print qq{'$1' '$2' '$3' '$4'}; " Use of uninitialized value $1 in concatenation (.) or string at -e lin +e 1. Use of uninitialized value $2 in concatenation (.) or string at -e lin +e 1. Use of uninitialized value $3 in concatenation (.) or string at -e lin +e 1. Use of uninitialized value $4 in concatenation (.) or string at -e lin +e 1. '' '' '' '' Use of uninitialized value $2 in concatenation (.) or string at -e lin +e 1. Use of uninitialized value $3 in concatenation (.) or string at -e lin +e 1. Use of uninitialized value $4 in concatenation (.) or string at -e lin +e 1. 'Three,' '' '' ''
Why does the first regex match nothing at all? (That should be fairly easy to answer: take a careful look at it.) Why does the second regex match something, but only once when you want it to match several times? Why does 'Three,' have a comma at the end? Do you really want to capture this character?
Update 1: Another thing to remember is that each successful regex match (and a s/// substitution must do a match — and you're doing four s/// in a row) that is executed "wipes out" all capture variables $1 $2 $3 $n and only re-assigns those corresponding to an actual capture group in the latest successful match.
c:\@Work\Perl\monks>perl -wMstrict -le "my $s = 'foo bar baz'; $s =~ m{ (foo) \s* (bar) \s* (baz) }xms; print qq{A: '$1' '$2' '$3'}; ;; $s =~ m{ (xyzzy) }xms; print qq{B: '$1' '$2' '$3'}; ;; $s =~ m{ (b \w*) }xms; print qq{C: '$1' '$2' '$3'}; " A: 'foo' 'bar' 'baz' B: 'foo' 'bar' 'baz' Use of uninitialized value $2 in concatenation (.) or string at -e lin +e 1. Use of uninitialized value $3 in concatenation (.) or string at -e lin +e 1. C: 'bar' '' ''
Update 2: Here's an approach (one of many) to the problem, but without the annoying <STDIN> stuff:
c:\@Work\Perl\monks>perl -wMstrict -le "my $s = 'Three, Four, One, Two, xFive9'; print qq{'$s'}; ;; my @numbers = $s =~ m{ \b [[:upper:]] [[:lower:]]+ \b }xmsg; printf qq{'$_' } for @numbers; print ''; ;; my %correct; @correct{ @numbers } = qw(one two three four); ;; my ($rx_search) = map qr{ \b (?: $_) \b }xms, join '|', map quotemeta, keys %correct ; print $rx_search; ;; $s =~ s{ ($rx_search) }{$correct{$1}}xmsg; print qq{'$s'}; " 'Three, Four, One, Two, xFive9' 'Three' 'Four' 'One' 'Two' (?^msx: \b (?: Four|Three|Two|One) \b ) 'one, two, three, four, xFive9'
In reply to Re: RegExp substitution
by AnomalousMonk
in thread RegExp substitution
by Keystone
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |