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

If you could give us the contents of the array you wish 'gat_12345' to be split into, we can perhaps give you some useful answers. Now we are just second guessing you.

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

  • Comment on Re: how can i split a string to an array and convert it into regular expression
  • Download Code

Replies are listed 'Best First'.
Re^2: how can i split a string to an array and convert it into regular expression
by Anonymous Monk on Dec 08, 2007 at 19:31 UTC
    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.

      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);
      You have not clearly described how you want the program to infer what regular expression to generate from the input.
      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