http://qs1969.pair.com?node_id=1227621


in reply to Search and replace regex, but only retain a portion of the string

Using two substitutions is cleaner:
$dest =~ s/\W+\[MSRN\]|\W+/_/g; $dest =~ s/_$//;
i.e. replace sequences of non-word characters by underscores, then remove the last underscore.

I can't think of a non-hackish solution with one substitution only.

$dest =~ s/(?:\W+(?:MSRN\])?|\W+)(?(?=$)(?{$%=1})|(?{$%=0}))/$%?'' +:'_'/ge;
map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Search and replace regex, but only retain a portion of the string
by ghenry (Vicar) on Dec 23, 2018 at 13:43 UTC

    Of course. For goodness sake, an OR. Thanks a lot! I can live with <code>_</code.