I am learning Perl and practicing regexes and I want to have the following functionality:
Wildcard style shell syntax
Perl regex
I am well aware of Regexp::Wildcards but I want something smaller and I also want to write it myself for the educational benefit.
I am really stuck trying to write the regex for this. I have tried to list my requirements to help make the regex pattern reveal itself:
However, this just introduced more questions in my mind
Suppose the input is {foo, bar}.c
. The substitute operator should transform this to (foo|bar).c
.
You don't keep a dynamic list of back references.
Instead, you break up this problem into steps:
my $string = "{a, b, c, d, ..., x}";
if ($string =~ m/\{(.*?)\}/) {
my $str = join '|', split /,\s*/, $1;
print "($str)";
}
Outputs:
(a|b|c|d|...|x)
It's also possible to do this using a double layer search and replace, like so:
$string =~ s{\{(.*?)\}}{
my $list = $1;
$list =~ s/,\s*/|/g;
"($list)"
}eg;
print $string;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With