in reply to Re: how can i split a string to an array and convert it into regular expression
in thread how can i split a string to an array and convert it into regular expression

the array should contain (g,a,t,_,1,2,3,4,5)
and the regex should be like /\b\w+_\d+\b/i
Thanks for your help.
  • Comment on Re^2: how can i split a string to an array and convert it into regular expression

Replies are listed 'Best First'.
Re^3: how can i split a string to an array and convert it into regular expression
by ikegami (Patriarch) on Dec 08, 2007 at 19:38 UTC

    To seperate the string into individual characters, you can use

    my @array = $string =~ /./g;
    or
    my @array = map /./g, $string;
    or
    my @array = split(//, $string);
Re^3: how can i split a string to an array and convert it into regular expression
by runrig (Abbot) on Dec 08, 2007 at 19:55 UTC
    You have not clearly described how you want the program to infer what regular expression to generate from the input.
Re^3: how can i split a string to an array and convert it into regular expression
by plobsing (Friar) on Dec 08, 2007 at 20:02 UTC
    Your regex groups characters using the + operator. Splitting into a list isn't the first way I would try this. Instead, I might try:
    my @groups = qw'[a-zA-Z]+ \d+ \s+'; my $matcher_pattern = join('|', (map {"($_)"} @groups, '.')); my $pattern = ''; MATCH: while ($string =~ /$matcher_pattern/g) { no strict 'refs'; for my $index (1.. scalar @groups) { if ($$index) { $pattern .= $groups[$index - 1]; next MATCH; } } $pattern .= quotemeta ${scalar @groups + 1}; } $regex = qr/$pattern/
    Update:Fixed off by one error. Update 2:Fixed metachar issue