Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > Perl Beginners > Re: howto simpl...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 2 of 5 Topic 11023 of 11518
Post > Topic >>

Re: howto simplfy this regex if ($string =~/^$match | $match | $match$/g){

by chas.owens@[EMAIL PROTECTED] (Chas. Owens) May 4, 2008 at 01:29 AM

On Sun, May 4, 2008 at 1:19 AM,  <itshardtogetone@[EMAIL PROTECTED]
> wrote:
> Hi,
>  How do I simplify the regex below so that it matches only the number 1,
henceforth it should return false if I match $string with $match.
>
>  use strict;
>  use warnings;
>
>  my $string = "10 11 12 13 40";
>  my $match = 1;
>
>  if ($string =~/^$match | $match | $match$/g){
>     print "match";
>  }else{
>    print "unmatch";
>  };
>

I may be missing something, but I believe you will get the same
results with just

if ($string =~ /$match/) {
    print "match\n";
} else {
    print "no match\n";
}

However, if you are going to include a string in a regex you should
probably use the \Q and \E modifiers* to prevent any metacharacters
(., *, ?, etc.) in the string from being interpreted by the regex
(unless, of course, that is what you want):

if ($string =~ /\Q$match\E/) {
    print "match\n";
} else {
    print "no match\n";
}

If you are going to use the same string in a regex multiple times you
are better off compiling it as a regex with the qr// operator** first:

my $match = qr/1/;

* http://perldoc.perl.org/perlre.html#Regular-Expressions
** http://perldoc.perl.org/perlop.html#qr%2fSTRING%2fmsixpo

-- 
Chas. Owens
wonkden.net
The most im****tant skill a programmer can have is the ability to read.
 




 5 Posts in Topic:
howto simplfy this regex if ($string =~/^$match | $match | $matc
itshardtogetone@[EMAIL PR  2008-05-04 13:19:50 
Re: howto simplfy this regex if ($string =~/^$match | $match | $
chas.owens@[EMAIL PROTECT  2008-05-04 01:29:02 
Re: howto simplfy this regex if ($string =~/^$match | $match | $
chas.owens@[EMAIL PROTECT  2008-05-04 01:47:28 
Re: howto simplfy this regex if ($string =~/^$match | $match | $
noreply@[EMAIL PROTECTED]  2008-05-04 08:05:48 
Re: howto simplfy this regex if ($string =~/^$match | $match | $
noreply@[EMAIL PROTECTED]  2008-05-04 07:45:22 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Thu Jul 24 13:12:48 CDT 2008.