in reply to Quick regex substitution question

Here's a look-ahead assertion that ought to do what you need. It looks for a ';' with anything after it between another ';', and replaces the first one. When it hits the last one, there's no more characters before another ';', so it has nothing else to substitute.

EDIT: It does not hit end-of-line as I previously stated. This example will leave any chars following the last ';', if there's no other ';' before EOL.

#!/usr/bin/perl use warnings; use strict; my $string = "I have; in my string; replace all but last one;"; $string =~ s/;(?=.*;)//g; print $string;

Output:

./r.pl I have in my string replace all but last one;

-stevieb

Replies are listed 'Best First'.
Re^2: Quick regex substitution question
by stevieb (Canon) on May 29, 2015 at 21:15 UTC

    For the sake of people in the future reading this thread, you can use look ahead/behind to split() something, and retain the thing you split on.

    The following split() splits on either whitespace or nothing with a '.' before it. The whitespace, if present, is thrown away, but the dot is retained within each split() element.

    #!/usr/bin/perl my $string = "I have. In my string.Replace all but last one."; @parts = split(/(?<=\.)\s*/, $string); print "$_\n" for @parts; __END__ ./split.pl I have. In my string. Replace all but last one.

    -stevieb

Re^2: Quick regex substitution question
by jmmach80 (Initiate) on May 29, 2015 at 14:21 UTC

    Sweet, that looks like it did what I'm looking for. Thanks for the help!