http://www.perlmonks.org?node_id=991656

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

Hi Monk,
I have a query string whose possible values could be $str1 and $str2. The requirement is I have to enclose the value after like/not like clause by %.
Problem is $str1 is working but not $str2
Please help me with a regular expression which will match both $str1 and $str2

my $str1 = "(View like all data) AND (Path not like /usr/bin)"; # work +ing my $str2 = "(View like all data AND Path not like /usr/bin)"; # not working while ($str1 =~ /\(\s*[\W\w]+?(like|not like)\s+([^%][\w\W][^%]+?)\s*\ +)/) { my $new = "%".$2."%"; $str =~ s/$2/$new/; }

N.B: 'Path' and 'View' can not be hardcoded in the regex as they might be anything in my $str1 and $atr2,like 'Project', 'site' etc.
In both cases the final string should be :
$str1 = "(View like all %data%) AND (Path not like %/usr/bin%)"
$str2 = "(View like all %data% AND Path not like %/usr/bin%)"
Thanks .

Replies are listed 'Best First'.
Re: Regular expression to match query
by Kenosis (Priest) on Sep 04, 2012 at 18:13 UTC

    Perhaps the following will work for you:

    use Modern::Perl; my @strs = ( '(View like all data) AND (Path not like /usr/bin)', '(View like all data AND Path not like /usr/bin)' ); for (@strs) { s/all\s+([^)]+)(\)?\s+AND.+like\s+)([^)]+)/all %$1%$2%$3%/; say; }

    Output:

    (View like all %data%) AND (Path not like %/usr/bin%) (View like all %data% AND Path not like %/usr/bin%)

    Hope this helps!