slg_saravanan has asked for the wisdom of the Perl Monks concerning the following question:

Hi Friends !!!

I just want to know the regular expression which should return only "EMPNO=","DEPTNO=","JOB=" from the following query with set of placeholder values,

"select * from EMP where EMPNO=&eno and DEPTNO=&dno and JOB=&job".

The query may be dynamic,like it may contain even a single placeholder value like,

"select * from EMP where EMPNO=&eno"

I just need a general regular expression that should return the "EMPNO=","DEPTNO=","JOB=" variables from the query. [key point here is : take the variable which is residing before "&" and stop obtaining it when a space comes in. like "where EMPNO=&eno" before "&" it contains EMPNO=]

Could anyone please help me out in this ?

Thanks,
Warm Regards,
Saravanan

20070621 Janitored by Corion: Unlinkified bogus square-brackets-link

Replies are listed 'Best First'.
Re: Regular Expression Question !!!
by bart (Canon) on Jun 20, 2007 at 11:10 UTC
    I'd try a different approach.

    $sql = 'select * from EMP where EMPNO=&eno and DEPTNO=&dno and JOB=&jo +b'; my @fields; if (my($where) = $sql =~ /\swhere\s+(.*)/i) { @fields = map /(\S*)=&/, split /\sand\s/i, $where; }
    (In English: parse out the "where" expression. Split it into terms on the "and" keyword. For each term, see if it matches the pattern of an identifier followed by "=&" and keep the identifier if it does match.)

    Hmm, are you sure you want the "=" to be part of the match?

    p.s. This is in my opinion a somewhat fishy approach, as it depends strongly on the query being formatted in a specific way. This might suffice for your needs, if the SQL is indeed as restricted as it appears here. In other cases, I'd look at better SQL parsers, like SQL::Parser, or Ovid's article on tokenizing SQL on perl.com

      I tried as follows..

      $string = "select * from EMP where EMPNO=&eno and DEPTNO=&dno and JOB= +&job"; @arr = split('\s+',$string); foreach $i (@arr) { if($i =~ /\&/g) { @arr1 = split('&',$i); print $arr1[0]."\n"; } }


      its working fine..Thanks a lot for the support pals !! :)
Re: Regular Expression Question !!!
by citromatik (Curate) on Jun 20, 2007 at 10:29 UTC

    try this:

    print map {"$_\n"} ($str=~/\w+=/g);

    If you want to make sure that there is a "&" following the "=" sign, you can do this instead:

    my $out=''; while ($str=~/(\w+=)\&/g){$out.=sprintf "%s\n",$1}; print $out;
    print map {"$_\n"} ($str=~/(\w+=)\&/g); #Thanks nferraz

    Hope this helps!

    citromatik

      You don't have to iterate to get each variable; just put the returned values into an array:
      my @variables = $str =~ /(\w+\=)\&/g; print "$_\n" foreach @variables;