Think
Think

Reputation: 65

Perl Regex to Convert {a, b, c, ..., x} into (a|b|c|...|x)

I am learning Perl and practicing regexes and I want to have the following functionality:

Input

Wildcard style shell syntax

Output

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

Example

Suppose the input is {foo, bar}.c. The substitute operator should transform this to (foo|bar).c.

Upvotes: 5

Views: 139

Answers (1)

Miller
Miller

Reputation: 35208

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;

Upvotes: 4

Related Questions