Operating System - Linux
1753479 Members
4731 Online
108794 Solutions
New Discussion юеВ

Help Regarding Perl Regular Expression(Pattern Matching)

 
SOLVED
Go to solution
Pankaj Yadav_1
Frequent Advisor

Help Regarding Perl Regular Expression(Pattern Matching)

The expression is -->

if($x =~ /$y/g) {
#where $x=41 and $y=424143

Please tell me if the above expression will work ?
If not then how to match $x and $y ?
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor

Re: Help Regarding Perl Regular Expression(Pattern Matching)

HI:

If you are looking to see if the character string "41" held in $x exists in $y (anywhere) then:

# perl -le '$x=41;$y=424143;if ($y =~ /$x/g) {print "ok"}'

...will print "ok".

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: Help Regarding Perl Regular Expression(Pattern Matching)

Hi (again):

An excellent tour and summmary of Perl regular expression syntax, can be found here:

http://perldoc.perl.org/perlre.html

At it's end are additional references, including Jeffrey Friedl's "Mastering Regulare Expressions" --- an outstanding book on the subject.

Regards!

...JRF...
Hein van den Heuvel
Honored Contributor
Solution

Re: Help Regarding Perl Regular Expression(Pattern Matching)


Just to see whether a simple (non-wildcard) string is a substring of an other string you should NOT use a regular expression.

Instead, use the 'index' function which is made specifically for that and processes more efficiently:

Same example:
perl -le '$x=41;$y=424143;if (index($y,$x) >= 0 ) {print "ok"}'


(one of many) Online documentation:
#http://www.xav.com/perl/lib/Pod/perlfunc.html#item_index

hth,
Hein van den Heuvel
HvdH Performance Consulting


H.Merijn Brand (procura
Honored Contributor

Re: Help Regarding Perl Regular Expression(Pattern Matching)

And if that is the only thing and the only time you match that/a pattern in the target string, PLEASE drop the /g modifier, as it has many side effects.
The /g modifier is for global matches, and returns more matches if available, changing the context if needed. It also fiddles with global variables and string attributes, so you can match on from the last position with \G metacharacters. The /g modifier is related to the /c modifier.

# perldoc perlretut

About 52% or 1188 lines down is the explanation of /g and /c

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
Pankaj Yadav_1
Frequent Advisor

Re: Help Regarding Perl Regular Expression(Pattern Matching)

I got the solution by
perl -le '$x=41;$y=424143;if (index($y,$x) >= 0 ) {print "ok"}'

which is suggested by Hein van Den.

Thanks a lot to all of you.