Consider: word1.word2.worda-wordb-wordc.ext
Is there a regular expression capture and replace string that can be used to obtain as result: worda wordb wordc using perl compatible regular expressions?
I know you can capture the group of words a,b,c with: /. ?\.. ?\.(. ?)\.ext$/$1/, but I don't know how to additionally replace dash (-) characters by space ( ) characters only within that group.
CodePudding user response:
You could replace - with spaces using s/\-/ /g
my $string = "word1.word2.worda-wordb-wordc.ext";
$string =~ s/. ?\.. ?\.(. ?)\.ext$/$1/;
$string =~ s/\-/ /g;
print($string); # worda wordb wordc
CodePudding user response:
Can run another regex in the replacement side, under /e modifier
$string =~ s{. ?\.. ?\.(. ?)\.ext$}{ $1 =~ s/-/ /gr }e;
The regex inside the replacement side has to use /r modifier since $1 can't be changed.
CodePudding user response:
Desired result can be achieved in several ways:
Demonstration code provided bellow
regexmethod is commented outsplitmethod used by code
use strict;
use warnings;
use feature 'say';
my $str = 'word1.word2.worda-wordb-wordc.ext';
#$str =~ s!\w \.\w \.(.*?)\.ext!$1 =~ s/-/ /gr!e;
$str = (split('\.',$str))[2] =~ s/-/ /gr;
say $str;
CodePudding user response:
Using match join in perl:
my $str = 'word1.word2.worda-wordb-wordc.ext';
print join (' ', $str =~ /[^-.] (?=-)|(?<=-)[^-.] /g) . "\n";
Output:
worda wordb wordc
RegEx Details:
[^-.] (?=-): Match 1 of any character that is not-or.when it is followed by a-|: OR(?<=-)[^-.]: Match 1 of any character that is not-or.when it is preceded by a-
